forked from Zy143L/wskey
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wskey.py
483 lines (444 loc) · 16.4 KB
/
wskey.py
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
# -*- coding: utf-8 -*
'''
cron: 15 2 * * * wskey.py
new Env('wskey转换');
'''
import socket
import base64
import http.client
import json
import os
import sys
import logging
import time
import urllib.parse
logging.basicConfig(level=logging.INFO, format='%(message)s')
logger = logging.getLogger(__name__)
try:
import requests
except Exception as e:
logger.info(str(e) + "\n缺少requests模块, 请执行命令:pip3 install requests\n")
sys.exit(1)
os.environ['no_proxy'] = '*'
requests.packages.urllib3.disable_warnings()
try:
from notify import send
except:
logger.info("无推送文件")
ver = 1118
# 登录青龙 返回值 token
def get_qltoken(username, password):
logger.info("Token失效, 新登陆\n")
url = "http://127.0.0.1:{0}/api/login".format(port)
payload = {
'username': username,
'password': password
}
payload = json.dumps(payload)
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
try:
res = requests.post(url=url, headers=headers, data=payload)
token = json.loads(res.text)["data"]['token']
except:
logger.info("青龙登录失败, 请检查面板状态!")
te_xt = '青龙面板WSKEY转换登陆面板失败, 请检查面板状态.'
try:
send('WSKEY转换', te_xt)
except:
logger.info("通知发送失败")
sys.exit(1)
else:
return token
# 返回值 Token
def ql_login():
path = '/ql/config/auth.json'
if os.path.isfile(path):
with open(path, "r") as file:
auth = file.read()
file.close()
auth = json.loads(auth)
username = auth["username"]
password = auth["password"]
token = auth["token"]
if token == '':
return get_qltoken(username, password)
else:
url = "http://127.0.0.1:{0}/api/user".format(port)
headers = {
'Authorization': 'Bearer {0}'.format(token),
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38'
}
res = requests.get(url=url, headers=headers)
if res.status_code == 200:
return token
else:
return get_qltoken(username, password)
else:
logger.info("没有发现auth文件, 你这是青龙吗???")
sys.exit(0)
# 返回值 list[wskey]
def get_wskey():
if "JD_WSCK" in os.environ:
wskey_list = os.environ['JD_WSCK'].split('&')
if len(wskey_list) > 0:
return wskey_list
else:
logger.info("JD_WSCK变量未启用")
sys.exit(1)
else:
logger.info("未添加JD_WSCK变量")
sys.exit(0)
# 返回值 list[jd_cookie]
def get_ck():
if "JD_COOKIE" in os.environ:
ck_list = os.environ['JD_COOKIE'].split('&')
if len(ck_list) > 0:
return ck_list
else:
logger.info("JD_COOKIE变量未启用")
sys.exit(1)
else:
logger.info("未添加JD_COOKIE变量")
sys.exit(0)
# 返回值 bool
def check_ck(ck):
if "QL_WSCK" in os.environ:
logger.info("不检查账号有效性\n--------------------\n")
return False
else:
url = 'https://wq.jd.com/user_new/info/GetJDUserInfoUnion?orgFlag=JD_PinGou_New&callSource=mainorder'
headers = {
'Cookie': ck,
'Referer': 'https://home.m.jd.com/myJd/home.action',
'user-agent': ua
}
try:
res = requests.get(url=url, headers=headers, verify=False, timeout=10)
except:
# logger.info("JD接口错误, 切换第二接口")
url = 'https://me-api.jd.com/user_new/info/GetJDUserInfoUnion'
headers = {
'Cookie': ck,
'user-agent': ua,
'Referer': 'https://home.m.jd.com/myJd/home.action'
}
res = requests.get(url=url, headers=headers, verify=False, timeout=30)
if res.status_code == 200:
code = int(json.loads(res.text)['retcode'])
pin = ck.split(";")[1]
if code == 0:
logger.info(str(pin) + ";状态正常\n")
return True
else:
logger.info(str(pin) + ";状态失效\n")
return False
else:
logger.info("JD接口错误码: " + str(res.status_code))
return False
else:
if res.status_code == 200:
code = int(json.loads(res.text)['retcode'])
pin = ck.split(";")[1]
if code == 0:
logger.info(str(pin) + ";状态正常\n")
return True
else:
logger.info(str(pin) + ";状态失效\n")
return False
else:
logger.info("JD接口错误码: " + str(res.status_code))
return False
# 返回值 bool jd_ck
def getToken(wskey):
headers = {
'cookie': wskey,
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
'charset': 'UTF-8',
'accept-encoding': 'br,gzip,deflate',
'user-agent': ua
}
params = {
'functionId': 'genToken',
'clientVersion': '10.2.2',
'client': 'android',
'uuid': uuid,
'st': st,
'sign': sign,
'sv': sv
}
url = 'https://api.m.jd.com/client.action'
data = 'body=%7B%22action%22%3A%22to%22%2C%22to%22%3A%22https%253A%252F%252Fplogin.m.jd.com%252Fcgi-bin%252Fm%252Fthirdapp_auth_page%253Ftoken%253DAAEAIEijIw6wxF2s3bNKF0bmGsI8xfw6hkQT6Ui2QVP7z1Xg%2526client_type%253Dandroid%2526appid%253D879%2526appup_type%253D1%22%7D&'
try:
res = requests.post(url=url, params=params, headers=headers, data=data, verify=False, timeout=10)
res_json = json.loads(res.text)
tokenKey = res_json['tokenKey']
except:
logger.info("WSKEY转换接口出错, 请稍后尝试, 脚本退出")
sys.exit(1)
else:
return appjmp(wskey, tokenKey)
# 返回值 bool jd_ck
def appjmp(wskey, tokenKey):
headers = {
'User-Agent': ua,
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
}
params = {
'tokenKey': tokenKey,
'to': 'https://plogin.m.jd.com/cgi-bin/m/thirdapp_auth_page?token=AAEAIEijIw6wxF2s3bNKF0bmGsI8xfw6hkQT6Ui2QVP7z1Xg',
'client_type': 'android',
'appid': 879,
'appup_type': 1,
}
url = 'https://un.m.jd.com/cgi-bin/app/appjmp'
try:
res = requests.get(url=url, headers=headers, params=params, verify=False, allow_redirects=False, timeout=20)
res_set = res.cookies.get_dict()
pt_key = 'pt_key=' + res_set['pt_key']
pt_pin = 'pt_pin=' + res_set['pt_pin']
jd_ck = str(pt_key) + ';' + str(pt_pin) + ';'
wskey = wskey.split(";")[0]
if 'fake' in pt_key:
logger.info(str(wskey) + ";WsKey状态失效\n")
return False, jd_ck
else:
logger.info(str(wskey) + ";WsKey状态正常\n")
return True, jd_ck
except:
logger.info("JD接口转换失败, 默认WsKey失效\n")
wskey = "pt_" + str(wskey.split(";")[0])
return False, wskey
# 返回值 svv, stt, suid, jign
def get_sign():
url = str(base64.b64decode('aHR0cDovLzQzLjEzNS45MC4yMy93c2tleQ==').decode())
for i in range(3):
try:
headers = {
"User-Agent": ua,
"Connection": "close"
}
res = requests.get(url=url, headers=headers, verify=False, timeout=20)
except requests.exceptions.ConnectTimeout:
logger.info("\n获取Sign超时, 正在重试!" + str(i))
time.sleep(1)
continue
except requests.exceptions.ReadTimeout:
logger.info("\n获取Sign超时, 正在重试!" + str(i))
time.sleep(1)
continue
except Exception as err:
logger.info(str(err) + "\n未知错误, 重试脚本!")
continue
else:
try:
sign_list = json.loads(res.text)
except:
logger.info("Sign Json错误")
sys.exit(1)
else:
svv = sign_list['sv']
stt = sign_list['st']
suid = sign_list['uuid']
jign = sign_list['sign']
return svv, stt, suid, jign
# 返回值 None
def boom():
ex = int(cloud_arg['code'])
if ex != 200:
logger.info("Check Failure")
logger.info("--------------------\n")
sys.exit(0)
else:
logger.info("Verification passed")
logger.info("--------------------\n")
def update():
up_ver = int(cloud_arg['update'])
if ver >= up_ver:
logger.info("当前脚本版本: " + str(ver))
logger.info("--------------------\n")
else:
logger.info("当前脚本版本: " + str(ver) + "新版本: " + str(up_ver))
logger.info("存在新版本, 请更新脚本后执行")
logger.info("--------------------\n")
text = '当前脚本版本: {0}新版本: {1}, 请更新脚本~!'.format(ver, up_ver)
try:
send('WSKEY转换', text)
except:
logger.info("通知发送失败")
# sys.exit(0)
def ql_check(port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2)
try:
sock.connect(('127.0.0.1', port))
except:
sock.close()
return False
else:
sock.close()
return True
# 返回值 bool, key, eid
def serch_ck(pin):
if all('\u4e00' <= char <= '\u9fff' for char in pin):
pin1 = urllib.parse.quote(pin)
pin2 = pin1.replace('%', '%5C%25')
logger.info(str(pin) + "-->" + str(pin1))
else:
pin2 = pin.replace('%', '%5C%25')
# TMD 中文!
# url = "http://127.0.0.1:5700/api/envs?searchValue={0}".format(pin)
# res = json.loads(s.get(url, verify=False).text)
conn = http.client.HTTPConnection("127.0.0.1", port)
payload = ''
headers = {
'Authorization': 'Bearer ' + token
}
url = '/api/envs?searchValue={0}'.format(pin2)
conn.request("GET", url, payload, headers)
res = json.loads(conn.getresponse().read())
if len(res['data']) == 0:
logger.info(str(pin) + "检索失败\n")
return False, 1
elif len(res['data']) > 1:
logger.info(str(pin) + "存在重复, 取第一条, 请删除多余变量\n")
key = res['data'][0]['value']
eid = res['data'][0]['_id']
return True, key, eid
else:
logger.info(str(pin) + "检索成功\n")
key = res['data'][0]['value']
eid = res['data'][0]['_id']
return True, key, eid
def ql_update(e_id, n_ck):
url = 'http://127.0.0.1:{0}/api/envs'.format(port)
data = {
"name": "JD_COOKIE",
"value": n_ck,
"_id": e_id
}
data = json.dumps(data)
res = json.loads(s.put(url=url, data=data).text)
ql_enable(eid)
def ql_enable(e_id):
url = 'http://127.0.0.1:{0}/api/envs/enable'.format(port)
data = '["{0}"]'.format(e_id)
res = json.loads(s.put(url=url, data=data).text)
if res['code'] == 200:
logger.info("\n账号启用\n--------------------\n")
return True
else:
logger.info("\n账号启用失败\n--------------------\n")
return False
def ql_disable(e_id):
url = 'http://127.0.0.1:{0}/api/envs/disable'.format(port)
data = '["{0}"]'.format(e_id)
res = json.loads(s.put(url=url, data=data).text)
if res['code'] == 200:
logger.info("\n账号禁用成功\n--------------------\n")
return True
else:
logger.info("\n账号禁用失败\n--------------------\n")
return False
def ql_insert(i_ck):
data = [{"value": i_ck, "name": "JD_COOKIE"}]
data = json.dumps(data)
url = 'http://127.0.0.1:{0}/api/envs'.format(port)
s.post(url=url, data=data)
logger.info("\n账号添加完成\n--------------------\n")
def cloud_info():
url = str(base64.b64decode('aHR0cDovLzQzLjEzNS45MC4yMy9jaGVja19hcGk=').decode())
for i in range(3):
try:
headers = {
"authorization": "Bearer Shizuku",
"Connection": "close"
}
res = requests.get(url=url, verify=False, headers=headers, timeout=20).text
except requests.exceptions.ConnectTimeout:
logger.info("\n获取云端参数超时, 正在重试!" + str(i))
except requests.exceptions.ReadTimeout:
logger.info("\n获取云端参数超时, 正在重试!" + str(i))
except Exception as err:
logger.info(str(err) + "\n未知错误云端, 退出脚本!")
sys.exit(1)
else:
try:
c_info = json.loads(res)
except:
logger.info("云端参数解析失败")
sys.exit(1)
else:
return c_info
if __name__ == '__main__':
logger.info("\n--------------------\n")
if "QL_PORT" in os.environ:
try:
port = int(os.environ['QL_PORT'])
except:
logger.info("变量格式有问题...\n格式: export QL_PORT=\"端口号\"")
sys.exit(1)
else:
port = 5700
if not ql_check(port):
logger.info(str(port) + "端口检查失败, 如果改过端口, 请在变量中声明端口 \n在config.sh中加入 export QL_PORT=\"端口号\"")
logger.info("\n如果你很确定端口没错, 还是无法执行, 在GitHub给我发issus\n--------------------\n")
sys.exit(1)
else:
logger.info(str(port) + "端口检查通过\n")
# global cloud_arg
token = ql_login() # 获取青龙 token
s = requests.session()
s.headers.update({"authorization": "Bearer " + str(token)})
s.headers.update({"Content-Type": "application/json;charset=UTF-8"})
cloud_arg = cloud_info()
update()
boom()
ua = cloud_arg['User-Agent']
sv, st, uuid, sign = get_sign()
wslist = get_wskey()
for ws in wslist:
wspin = ws.split(";")[0]
if "pin" in wspin:
wspin = "pt_" + wspin + ";" # 封闭变量
return_serch = serch_ck(wspin) # 变量 pt_pin 搜索获取 key eid
if return_serch[0]: # bool: True 搜索到账号
jck = str(return_serch[1]) # 拿到 JD_COOKIE
if not check_ck(jck): # bool: False 判定 JD_COOKIE 有效性
return_ws = getToken(ws) # 使用 WSKEY 请求获取 JD_COOKIE bool jd_ck
if return_ws[0]: # bool: True
nt_key = str(return_ws[1])
# logger.info("wskey转pt_key成功", nt_key)
logger.info("wskey转换成功")
eid = return_serch[2] # 从 return_serch 拿到 eid
ql_update(eid, nt_key) # 函数 ql_update 参数 eid JD_COOKIE
else:
# logger.info(str(wspin) + "wskey失效\n")
eid = return_serch[2]
logger.info(str(wspin) + "账号禁用")
ql_disable(eid)
# dd = serch_ck(ws)[2]
# ql_disable(dd)
text = "账号: {0} WsKey失效, 已禁用Cookie".format(wspin)
try:
send('WsKey转换脚本', text)
except:
logger.info("通知发送失败")
else:
logger.info(str(wspin) + "账号有效")
eid = return_serch[2]
ql_enable(eid)
logger.info("--------------------\n")
else:
logger.info("\n新wskey\n")
return_ws = getToken(ws) # 使用 WSKEY 请求获取 JD_COOKIE bool jd_ck
if return_ws[0]:
nt_key = str(return_ws[1])
logger.info("wskey转换成功\n")
ql_insert(nt_key)
else:
logger.info("WSKEY格式错误\n--------------------\n")
logger.info("执行完成\n--------------------")
sys.exit(0)