-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwait-save-token-once.py
More file actions
58 lines (51 loc) · 1.79 KB
/
wait-save-token-once.py
File metadata and controls
58 lines (51 loc) · 1.79 KB
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
# save_token_once.py
"""
mitmproxy addon: 抓到第一个 token 就打印、写文件并退出 (one-shot)
用法: mitmdump -s save_token_once.py
"""
from mitmproxy import http, ctx
import json, os
# 配置区
TARGET_HOST = "discount.wxpapp.wechatpay.cn" # <- 改成你要抓的域名,或设为 None 捕获所有 host
OUTFILE = "session_token.txt" # 输出文件(相对 mitmdump 启动目录)
# helper: 写并打印
def save_and_exit(token):
abspath = os.path.abspath(OUTFILE)
try:
with open(OUTFILE, "w", encoding="utf-8") as f:
f.write(token)
except Exception as e:
print(f"[save_token_once] write error: {e}")
print(f"[save_token_once] found token: {token[:24]}... (len={len(token)})")
print(f"[save_token_once] written to: {abspath}")
# 尝试优雅退出 mitmproxy
try:
print("[save_token_once] shutting down mitmdump...")
ctx.master.shutdown()
except Exception:
# 兼容性回退:抛出异常让 mitmdump 退出(不常用)
raise SystemExit(0)
def response(flow: http.HTTPFlow) -> None:
# 过滤 host(可注释掉以捕获所有响应)
try:
host = flow.request.host
except Exception:
host = None
if TARGET_HOST and host != TARGET_HOST:
return
# 尝试解析 JSON 响应体
try:
text = flow.response.get_text()
data = json.loads(text)
except Exception:
return
# 提取常见字段
token = None
if isinstance(data, dict):
d = data.get("data")
if isinstance(d, dict):
token = d.get("session_token") or d.get("sessionToken") or d.get("session-token")
if not token:
token = data.get("session_token") or data.get("token")
if token:
save_and_exit(token)