#!/usr/bin/env python3 # -*- coding: utf-8 -*- """康意 mom-kyzn 全量接口 500 扫描(基于 /v3/api-docs 自动发现)""" import json, sys, re, time, urllib.request, urllib.error, concurrent.futures BASE = "http://127.0.0.1:9007" TOKEN = sys.argv[1] TENANT = "1" def load_doc(url): req = urllib.request.Request(url, headers={"Accept": "application/json"}) with urllib.request.urlopen(req, timeout=120) as r: return json.loads(r.read().decode("utf-8")) def collect(): cfg = load_doc(BASE + "/v3/api-docs/swagger-config") ops = [] seen = set() for u in cfg.get("urls", []): try: doc = load_doc(BASE + u["url"]) except Exception as e: print("SKIP doc", u["url"], e) continue paths = doc.get("paths", {}) for path, methods in paths.items(): for m, op in methods.items(): if m.lower() not in ("get", "post", "put", "delete"): continue if path in seen: continue seen.add(path + " " + m) ops.append((m.upper(), path, op.get("operationId", ""))) return ops def call(op): m, path, oid = op # 替换路径参数为 1 real = re.sub(r"\{[^/}]+\}", "1", path) url = BASE + real data = None headers = {"Authorization": "Bearer " + TOKEN, "tenant-id": TENANT} if m in ("POST", "PUT"): data = b"{}" headers["Content-Type"] = "application/json" req = urllib.request.Request(url, data=data, headers=headers, method=m) t0 = time.time() try: with urllib.request.urlopen(req, timeout=60) as r: body = r.read(4000).decode("utf-8", "replace") code = r.status except urllib.error.HTTPError as e: body = e.read(4000).decode("utf-8", "replace") code = e.code except Exception as e: return (m, path, oid, "EXC", str(e)[:120], int((time.time()-t0)*1000)) try: j = json.loads(body) biz = j.get("code") msg = (j.get("msg") or "")[:160] except Exception: biz, msg = None, body[:160] return (m, path, oid, biz if biz is not None else code, msg, int((time.time()-t0)*1000)) def main(): ops = collect() print("TOTAL_OPS", len(ops), flush=True) results = [] with concurrent.futures.ThreadPoolExecutor(max_workers=8) as ex: for r in ex.map(call, ops): results.append(r) bad500 = [r for r in results if r[3] == 500 or r[3] == "EXC"] others = {} for r in results: others[str(r[3])] = others.get(str(r[3]), 0) + 1 print("STATS", json.dumps(others, ensure_ascii=False), flush=True) print("===== 500 LIST =====", flush=True) for r in sorted(bad500, key=lambda x: x[1]): print("%s %s | op=%s | code=%s | %s | %sms" % r, flush=True) print("500_COUNT", len(bad500), flush=True) with open("/tmp/kyzn_probe_all.json", "w") as f: json.dump([{"method": r[0], "path": r[1], "op": r[2], "code": r[3], "msg": r[4], "ms": r[5]} for r in results], f, ensure_ascii=False, indent=1) main()