feat: 新增交通银行数据导出插件及测试通道机制

This commit is contained in:
2026-11-05 15:20:34 +08:00
parent b976b80d9d
commit 4e8b3e7d43
230 changed files with 19827 additions and 1440 deletions
+342
View File
@@ -0,0 +1,342 @@
# -*- coding: utf-8 -*-
"""交行商户服务门户(merchantapp.bankcomm.com/mm)一次性抓包探针。
作用:
打开登录页,附随人工完成「登录 + 导出报表」全过程,把页面产生的全部网络请求
(请求头 / postData / 响应体,脚本/图片等静态资源只记 URL 不记 body)逐条落盘为
JSONL;同时接管浏览器下载目录,把手工点「导出」得到的文件保存下来。
跑完由人(或 AI)分析登录链路与导出链路,判定是否真需要 JS 逆向。
产出(logs/bankcomm_probe/,已被 .gitignore 的 logs/ 规则忽略):
capture_<时间戳>.jsonl 全量抓包(每行一个请求;含 Cookie,勿外传)
summary_<时间戳>.json 运行摘要(接口清单去重、下载文件、结束原因)
downloads/ 浏览器下载文件(手动点导出也落到这里)
结束条件(任一):
1. 已离开登录页 且 捕获到下载 且 连续空闲 90s;
2. 已离开登录页 且 连续空闲 270s(没捕获到下载时的兜底);
3. 总时长超过 45 分钟;
4. 浏览器被手动关闭。
用法(仓库根目录执行):
.venv\\Scripts\\python.exe tests\\bankcomm_probe\\bankcomm_capture.py
"""
import json
import os
import sys
import time
try: # 重定向到文件时避免 GBK 崩中文
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
sys.stderr.reconfigure(encoding='utf-8', errors='replace')
except Exception:
pass
from DrissionPage import ChromiumPage, ChromiumOptions
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
PROBE_DIR = os.path.join(REPO_ROOT, 'logs', 'bankcomm_probe')
DOWNLOAD_DIR = os.path.join(PROBE_DIR, 'downloads')
PROFILE_DIR = os.path.join(os.environ.get('LOCALAPPDATA') or PROBE_DIR,
'37duAutomation', 'browser_sessions', 'bankcomm_probe')
LOGIN_URL = 'https://merchantapp.bankcomm.com/mm/#/login'
LOCAL_PORT = 9333
MAX_SECONDS = 45 * 60
IDLE_STOP = 90
IDLE_STOP_NO_DL = 270
BODY_LIMIT = 20000
POST_LIMIT = 8000
BODY_SKIP_RT = {'IMAGE', 'FONT', 'STYLESHEET', 'MEDIA', 'SCRIPT', 'MANIFEST', 'OTHER'}
TALLY_RT = {'XHR', 'FETCH', 'DOCUMENT', 'EVENTSOURCE'}
def now_str():
return time.strftime('%Y-%m-%d %H:%M:%S')
def log(msg, level='INFO'):
print(f'[{now_str()}] [{level}] {msg}', flush=True)
def _hdrs(obj):
try:
return {str(k): str(v) for k, v in dict(obj).items()}
except Exception:
return {}
def _is_login_url(url):
u = (url or '').lower()
return '#/login' in u or u.rstrip('/').endswith('/login') or 'login' in u.split('?')[0].rsplit('/', 1)[-1]
def _wait(tab, timeout=0.2):
try:
return tab.listen.wait(timeout=timeout, raise_err=False)
except Exception:
return False
def _packet_to_rec(p):
"""DataPacket -> 落盘字典;非 http(s) 直接丢弃。"""
try:
url = p.url or ''
except Exception:
return None
if not url.lower().startswith(('http://', 'https://')):
return None
rt = getattr(p, 'resourceType', None)
rec = {'kind': 'req', 'method': getattr(p, 'method', '') or '', 'url': url, 'rtype': rt}
try:
rec['req_headers'] = _hdrs(p.request.headers)
except Exception:
rec['req_headers'] = {}
try:
pd = p.request.postData
if pd:
s = json.dumps(pd, ensure_ascii=False, default=str) if isinstance(pd, (dict, list)) else str(pd)
rec['post_data'] = s[:POST_LIMIT]
rec['post_len'] = len(s)
except Exception:
pass
if getattr(p, 'is_failed', False):
rec['failed'] = True
try:
rec['fail_info'] = str(p.fail_info)
except Exception:
pass
return rec
try:
rec['status'] = p.response.status
rec['resp_headers'] = _hdrs(p.response.headers)
except Exception:
pass
if (rt or '').upper() not in BODY_SKIP_RT:
try:
b = p.response.body
except Exception:
b = None
if b is not None:
if isinstance(b, (dict, list)):
s = json.dumps(b, ensure_ascii=False, default=str)
elif isinstance(b, bytes):
s = ''
rec['body_bytes'] = len(b)
else:
s = str(b)
if s:
rec['body'] = s[:BODY_LIMIT]
rec['body_len'] = len(s)
rec['body_truncated'] = len(s) > BODY_LIMIT
return rec
def _tally(stats, rec):
if (rec.get('rtype') or '').upper() not in TALLY_RT:
return
path = rec['url'].split('?')[0]
key = f"{rec.get('method')} {path}"
item = stats['api'].setdefault(key, {'count': 0, 'sample': rec['url']})
item['count'] += 1
def main():
for d in (PROBE_DIR, DOWNLOAD_DIR, PROFILE_DIR):
os.makedirs(d, exist_ok=True)
ts = time.strftime('%Y%m%d_%H%M%S')
cap_path = os.path.join(PROBE_DIR, f'capture_{ts}.jsonl')
sum_path = os.path.join(PROBE_DIR, f'summary_{ts}.json')
cap = open(cap_path, 'w', encoding='utf-8', buffering=1)
stats = {'packets': 0, 'api': {}}
def emit(rec):
rec.setdefault('ts', now_str())
cap.write(json.dumps(rec, ensure_ascii=False) + '\n')
log(f'抓包文件: {cap_path}')
log(f'下载目录: {DOWNLOAD_DIR}')
log(f'浏览器 profile: {PROFILE_DIR}')
co = ChromiumOptions()
co.set_local_port(LOCAL_PORT)
co.set_user_data_path(PROFILE_DIR)
co.set_argument('--start-maximized')
try:
co.set_pref('credentials_enable_service', False)
co.set_pref('profile.password_manager_enabled', False)
except Exception:
pass
try:
co.set_download_path(DOWNLOAD_DIR)
except Exception as e:
log(f'ChromiumOptions.set_download_path 不可用(稍后用 page 设置):{e}', 'WARN')
page = ChromiumPage(co)
try:
page.set.download_path(DOWNLOAD_DIR)
page.set.when_download_file_exists('rename')
except Exception as e:
log(f'page.set.download_path 失败:{e}', 'WARN')
listeners = {}
def attach(tab, tid=None):
tid = tid or getattr(tab, 'tab_id', None)
try:
tab.listen.start(True, method=True)
listeners[tid] = tab
log(f'已挂载抓包 tab={tid}')
return True
except Exception as e:
log(f'挂载抓包失败 tab={tid}:{e}', 'WARN')
return False
attach(page)
page.get(LOGIN_URL)
log('=' * 70)
log('浏览器已打开交行商户门户登录页,请手动完成:登录 → 进入报表 → 点击导出。')
log('脚本在后台持续抓包,导出文件会自动落到 downloads/ 目录。')
log(f'结束条件:登录后捕获到下载再空闲 {IDLE_STOP}s 自动收尾(无下载则空闲 {IDLE_STOP_NO_DL}s)。')
log('=' * 70)
start = time.time()
last_active = time.time()
last_url = ''
dl_size = {}
dl_done = []
stop_reason = ''
try:
while True:
# 1) 抽取各 tab 已捕获的包
for tid, tab in list(listeners.items()):
packet = _wait(tab)
while packet:
try:
rec = _packet_to_rec(packet)
except Exception as e:
rec = None
log(f'解析数据包异常:{e}', 'DEBUG')
if rec:
emit(rec)
stats['packets'] += 1
_tally(stats, rec)
last_active = time.time()
packet = _wait(tab, 0.02)
# 2) 新标签页(导出若另开页,也挂上抓包)
try:
for tid in page.tab_ids:
if tid not in listeners:
t = page.get_tab(tid)
try:
u = t.url
except Exception:
u = ''
emit({'kind': 'tab', 'tab': tid, 'url': u})
attach(t, tid)
last_active = time.time()
except Exception:
pass
# 3) 主标签页 URL 变化(登录成功跳转会在这里体现)
try:
cur = page.latest_tab.url
except Exception:
stop_reason = '浏览器已关闭'
break
if cur != last_url:
if last_url:
log(f'页面跳转:{cur}')
last_url = cur
emit({'kind': 'nav', 'url': cur})
last_active = time.time()
# 4) 下载目录变化
try:
for name in os.listdir(DOWNLOAD_DIR):
p = os.path.join(DOWNLOAD_DIR, name)
if not os.path.isfile(p):
continue
size = os.path.getsize(p)
if name.endswith('.crdownload'):
if name not in dl_size:
dl_size[name] = -1
log(f'下载中:{name}')
last_active = time.time()
continue
prev = dl_size.get(name)
if prev != size:
dl_size[name] = size
last_active = time.time()
if prev is None:
log(f'检测到下载:{name}')
emit({'kind': 'download_start', 'name': name, 'size': size})
elif size > 0 and name not in dl_done:
dl_done.append(name)
emit({'kind': 'download_done', 'name': name, 'size': size})
log(f'下载完成:{name}({size} 字节)')
except Exception:
pass
# 5) 结束判定
idle = time.time() - last_active
logged_in = bool(last_url) and not _is_login_url(last_url)
has_dl = bool(dl_size)
if logged_in and has_dl and idle > IDLE_STOP:
stop_reason = f'已登录且捕获到下载,空闲 {int(idle)}s'
break
if logged_in and idle > IDLE_STOP_NO_DL:
stop_reason = f'已登录且空闲 {int(idle)}s(未捕获到下载)'
break
if time.time() - start > MAX_SECONDS:
stop_reason = f'达到总时长上限 {MAX_SECONDS}s'
break
time.sleep(0.3)
except KeyboardInterrupt:
stop_reason = '人工中断(Ctrl+C)'
finally:
summary = {
'login_url': LOGIN_URL,
'capture_file': cap_path,
'started_at': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(start)),
'ended_at': now_str(),
'duration_s': int(time.time() - start),
'stop_reason': stop_reason,
'final_url': last_url,
'packets': stats['packets'],
'downloads': dl_done,
'api_endpoints': [
{'api': k, 'count': v['count'], 'sample': v['sample']}
for k, v in sorted(stats['api'].items(), key=lambda kv: -kv[1]['count'])
],
}
try:
with open(sum_path, 'w', encoding='utf-8') as f:
json.dump(summary, f, ensure_ascii=False, indent=2)
except Exception as e:
log(f'写摘要失败:{e}', 'WARN')
try:
cap.close()
except Exception:
pass
log(f'抓包结束({stop_reason}):{stats["packets"]} 个包,{len(dl_done)} 个下载')
log(f'抓包文件:{cap_path}')
log(f'摘要文件:{sum_path}')
try:
page.quit()
except Exception:
pass
if __name__ == '__main__':
main()