-
Notifications
You must be signed in to change notification settings - Fork 0
/
2kStar.go
412 lines (363 loc) · 9.39 KB
/
2kStar.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
/*
* @Author: 2Kil
* @Date: 2024-04-19 10:54:20
* @LastEditors: 2Kil
* @LastEditTime: 2024-10-20 17:02:20
* @Description:tktar
*/
package tkstar
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
crand "crypto/rand"
"encoding/base64"
"fmt"
"io"
"log"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"sync/atomic"
"time"
"github.com/google/logger"
)
/**
* @description: 判断当前环境是否为Debug模式
* @return {bool} true:Debug模式 false:Release模式
*/
func IsDebug() bool {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
return false
}
if strings.Contains(dir, "Temp") && strings.Contains(dir, "go-build") {
log.Println("The current mode is debug")
return true
}
return false
}
/**
* @description: 生成随机数
* @param {int} max 最大值
* @return {int} 随机数
*/
func RandAtomic(max int) int {
var counter int64
rand.New(rand.NewSource(time.Now().UnixNano() + atomic.AddInt64(&counter, 1)))
randomNum := rand.Intn(max)
return randomNum
}
/**
* @description: 生成范围内的随机数
* @param {int} min 最小值
* @param {int} max 最大值
* @return {int} 随机数
*/
func RandAtomicRadius(min, max int) int {
if max <= min {
return min
}
var counter int64
rand.New(rand.NewSource(time.Now().UnixNano() + atomic.AddInt64(&counter, 1)))
randomNum := min + rand.Intn(max-min+1)
return randomNum
}
/**
* @description: 错误检测
* @param {error} err 错误信息
* @param {string} errString 自定义错误提示
* @return {bool} 无错误true 有错误false
*/
func CheckErr(err error, errString ...string) bool {
errString = append(errString, "Error")
if err != nil {
log.Println(errString, err)
return false
}
return true
}
/**
* @description: 输出编译时间
* @return {string} 当前文件编译时间
*/
func BuildTime() string {
// 获取当前程序的文件信息
fileInfo, err := os.Stat(os.Args[0])
if err != nil {
return "0.0.0.0"
}
// 获取修改时间
modTime := fileInfo.ModTime()
buildTime := modTime.Format("06.0102.1504")
// 打印修改时间
log.Printf("Build Time:%s", buildTime)
return buildTime
}
/**
* @description: 切片去重,去空
* @param {[]string} 待处理的切片
* @return {[]string} 处理后的切片
*/
func HelperRemoveDuplicates(s []string) []string {
m := make(map[string]bool)
var result []string
for _, item := range s {
if item == "" {
continue // 跳过空字符串
}
if _, ok := m[item]; !ok {
m[item] = true
result = append(result, item)
}
}
return result
}
/**
* @description: aes加密
* @param {string} 待加密的文本
* @param {string} 16,24,32密钥
* @return {string} 密文
*/
func TextAesEncrypt(plainText, key string) string {
block, err := aes.NewCipher([]byte(key))
if err != nil {
return ""
}
plainTextBytes := []byte(plainText)
cipherText := make([]byte, aes.BlockSize+len(plainTextBytes))
iv := cipherText[:aes.BlockSize]
if _, err := io.ReadFull(crand.Reader, iv); err != nil {
return ""
}
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(cipherText[aes.BlockSize:], plainTextBytes)
text := base64.StdEncoding.EncodeToString(cipherText)
//替换base64特殊字符
text = strings.ReplaceAll(text, "/", "*")
text = strings.ReplaceAll(text, "==", "#")
text = strings.ReplaceAll(text, "=", "$")
return text
}
/**
* @description: aes解密
* @param {string} 待解密的文本
* @param {string} 密钥
* @return {string} 明文
*/
func TextAesDecrypt(cipherText, key string) string {
//替换base64特殊字符
cipherText = strings.ReplaceAll(cipherText, "*", "/")
cipherText = strings.ReplaceAll(cipherText, "$", "=")
cipherText = strings.ReplaceAll(cipherText, "#", "==")
cipherTextBytes, err := base64.StdEncoding.DecodeString(cipherText)
if err != nil {
return ""
}
block, err := aes.NewCipher([]byte(key))
if err != nil {
return ""
}
if len(cipherTextBytes) < aes.BlockSize {
return ""
}
iv := cipherTextBytes[:aes.BlockSize]
cipherTextBytes = cipherTextBytes[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(block, iv)
stream.XORKeyStream(cipherTextBytes, cipherTextBytes)
return string(cipherTextBytes)
}
/**
* @description: 获取设备硬件码
* @return {string} 硬件码
*/
func SysGetSerialKey() string {
// 获取本机的MAC地址
var mac string
interfaces, err := net.Interfaces()
if err != nil {
mac = ""
} else {
mac = interfaces[0].HardwareAddr.String()
}
// 获取系统UUID
var uuid string
cmd := exec.Command("wmic", "csproduct", "get", "UUID")
uuidOut, err := cmd.Output()
if err != nil {
uuid = "FFFFFFFFF"
}
uuid = string(uuidOut)
// 获取硬盘串号
var diskSerial string
cmd = exec.Command("wmic", "diskdrive", "get", "SerialNumber")
diskSerialOut, err := cmd.Output()
if err != nil {
diskSerial = "6479_A771_20C0_1EFF"
}
diskSerial = string(diskSerialOut)
reg0 := strings.ToUpper(fmt.Sprintf("%x", md5.Sum([]byte(mac+uuid+diskSerial))))
// 简化设备码
return reg0[8:11] + reg0[2:3] + reg0[12:14]
}
/**
* @description:go的curl实现
* @param {string} cUrl(bash)格式的请求命令
* @return {*} 响应体
*/
func NetCurl(curlBash string) (int, string) {
// 解析curl命令
method, url, headers, data, err := NetParseCurlComd(curlBash)
if err != nil {
fmt.Println("Error parsing curl command:", err)
return 0, ""
}
// 创建一个HTTP POST请求
req, err := http.NewRequest(method, url, bytes.NewBuffer(data))
if err != nil {
fmt.Println("Error creating HTTP request:", err)
return 0, ""
}
// 设置HTTP头
req.Header = headers
// 如果你的数据体是JSON,并且你还没有设置Content-Type头,你可以在这里添加它
// req.Header.Set("Content-Type", "application/json")
// 发送HTTP请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Println("Error sending HTTP request:", err)
return 0, ""
}
defer resp.Body.Close()
// 读取并打印响应体
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Println("Error reading response body:", err)
return 0, ""
}
return resp.StatusCode, string(body)
}
/**
* @description:go的curl实现(走代理)
* @param {string} cUrl(bash)格式的请求命令
* @return {*} 响应体
*/
func NetProxyCurl(proxy, curlBash string) (int, string) {
// 解析curl命令
method, urll, headers, data, err := NetParseCurlComd(curlBash)
if err != nil {
fmt.Println("Error parsing curl command:", err)
return 0, ""
}
// 创建一个HTTP POST请求
req, err := http.NewRequest(method, urll, bytes.NewBuffer(data))
if err != nil {
fmt.Println("Error creating HTTP request:", err)
return 0, ""
}
// 设置HTTP头
req.Header = headers
// 发送HTTP请求
var client *http.Client
if proxy != "" {
// 解析代理URL
proxyURL, err := url.Parse(proxy)
if err != nil {
log.Fatalf("Failed to parse proxy URL: %v", err)
}
// 创建一个http.Transport,设置Proxy字段为之前解析的URL
transport := &http.Transport{
Proxy: http.ProxyURL(proxyURL),
}
// 创建一个http.Client,使用上面配置的Transport
client = &http.Client{
Transport: transport,
}
} else {
client = &http.Client{}
}
resp, err := client.Do(req)
if err != nil {
log.Println("Error sending HTTP request:", err)
return 0, ""
}
defer resp.Body.Close()
// 读取并打印响应体
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Println("Error reading response body:", err)
return 0, ""
}
return resp.StatusCode, string(body)
}
/**
* @description: 解析curl命令
* @param {string} curlCmd
* @return {*} 请求方法,请求地址,请求头,请求体,错误信息
*/
func NetParseCurlComd(curlCmd string) (string, string, http.Header, []byte, error) {
method := "GET"
// 提取URL
urlRe := regexp.MustCompile(`curl '([^']+)'`)
urlMatch := urlRe.FindStringSubmatch(curlCmd)
if len(urlMatch) != 2 {
return method, "", nil, nil, fmt.Errorf("failed to find URL in curl command")
}
rawURL := urlMatch[1]
parsedURL, err := url.Parse(rawURL)
if err != nil {
return method, "", nil, nil, err
}
// 提取HTTP头
headerRe := regexp.MustCompile(`-H '([^']+): ([^']+)'`)
headers := make(http.Header)
matches := headerRe.FindAllStringSubmatch(curlCmd, -1)
for _, match := range matches {
if len(match) != 3 {
continue
}
key, value := match[1], match[2]
headers.Set(key, value)
}
//提取请求方法
methodRe := regexp.MustCompile(`--request ([A-Za-z]+)`)
methodMatch := methodRe.FindStringSubmatch(curlCmd)
if len(methodMatch) >= 2 {
//获取到请求方法
method = methodMatch[1]
}
// 提取提交数据体
dataRe := regexp.MustCompile(`--data-raw '([^']+)'`)
dataMatch := dataRe.FindStringSubmatch(curlCmd)
if len(dataMatch) >= 2 {
rawData := []byte(dataMatch[1])
return method, parsedURL.String(), headers, rawData, nil
}
return method, parsedURL.String(), headers, nil, nil
}
/**
* @description: 记录日志到文件&系统事件
* @param {string} logFIle
* @param {bool} systemLog true写入系统事件
* @return {*}
*/
func LogFile(logFIle string,systemLog string) (*logger.Logger, error) {
// 创建一个文件用于写入日志
logFile, err := os.OpenFile(logFIle+".log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0660)
if err != nil {
logger.Fatalf("Failed to open log file: %v", err)
return nil, err
}
// defer logFile.Close()
loger := logger.Init(logFIle, true, true, logFile)
// defer loger.Close()
return loger, nil
}