aicds_probe_spu.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. # -*- coding: utf-8 -*-
  2. """爱云医 spu/page 探测脚本(联调用)。
  3. 用法:
  4. python aicds_probe_spu.py [手机号]
  5. 不带手机号: 仅做「无 token 直连」探测,验证 spu/page 是否强制要求登录。
  6. 带手机号: 走完整 identify 登录 → spu/page → 输出商品清单。
  7. 凭证从 /tmp/aiyunyi_creds.txt 读取(不入库、不打印)。
  8. """
  9. import re, sys, os, json, time, base64, subprocess, tempfile
  10. TMPDIR = tempfile.gettempdir() # Windows 下 = C:\Users\...\AppData\Local\Temp(Python与openssl同路径)
  11. CRED_PATH = os.environ.get("AICDS_CRED",
  12. r"C:\Users\liaoxg.DESKTOP-DGLN79N\AppData\Local\Temp\aiyunyi_creds.txt")
  13. BASE = "https://devadmin.aicds.com.cn/open-api"
  14. def load_cred():
  15. txt = open(CRED_PATH, encoding="utf-8", errors="ignore").read()
  16. appkey = re.search(r"API Key:\s*(\S+)", txt).group(1)
  17. priv = re.search(r"RSA \S+:\s*([A-Za-z0-9+/=]{100,})", txt).group(1)
  18. return appkey, priv
  19. APPKEY, PRIV = load_cred()
  20. PEM = os.path.join(TMPDIR, "aicds_probe_key.pem")
  21. def sign_headers():
  22. ts = str(int(time.time() * 1000))
  23. sign_str = "appKey=%s&timestamp=%s" % (APPKEY, ts)
  24. pem = ("-----BEGIN PRIVATE KEY-----\n"
  25. + "\n".join(PRIV[i:i+64] for i in range(0, len(PRIV), 64))
  26. + "\n-----END PRIVATE KEY-----\n")
  27. with open(PEM, "w") as f:
  28. f.write(pem)
  29. os.chmod(PEM, 0o600)
  30. raw = subprocess.run(["openssl", "dgst", "-sha256", "-sign", PEM],
  31. input=sign_str.encode(), capture_output=True)
  32. if raw.returncode != 0:
  33. print("签名失败:", raw.stderr.decode()); sys.exit(2)
  34. return ts, base64.b64encode(raw.stdout).decode()
  35. def call(method, path, token=None, uid_enc=None, body=None):
  36. ts, sign = sign_headers()
  37. cmd = ["curl", "-sS", "-m", "30", "-w", "\n__HTTP__%{http_code}",
  38. "-X", method, BASE + path,
  39. "-H", "X-App-Key: " + APPKEY,
  40. "-H", "X-Timestamp: " + ts,
  41. "-H", "X-Api-Sign: " + sign]
  42. if token:
  43. cmd += ["-H", "Authorization: Bearer " + token]
  44. if uid_enc:
  45. cmd += ["-H", "X-User-Id-Encrypt: " + uid_enc]
  46. cmd += ["-H", "Content-Type: application/json"]
  47. if body is not None:
  48. cmd += ["--data", json.dumps(body)]
  49. r = subprocess.run(cmd, capture_output=True)
  50. return r.stdout.decode(errors="ignore") + r.stderr.decode(errors="ignore")
  51. def encrypt_uid(user_id):
  52. """用租户 RSA 公钥 PKCS#1 加密 userId → Base64(X-User-Id-Encrypt)"""
  53. pub_b64 = re.search(r"RSA \S+:\s*([A-Za-z0-9+/=]{100,})",
  54. open(CRED_PATH, encoding="utf-8", errors="ignore").read()).group(1)
  55. pubpem = os.path.join(TMPDIR, "aicds_probe_pub.pem")
  56. with open(pubpem, "w") as f:
  57. f.write("-----BEGIN PUBLIC KEY-----\n"
  58. + "\n".join(pub_b64[i:i+64] for i in range(0, len(pub_b64), 64))
  59. + "\n-----END PUBLIC KEY-----\n")
  60. raw = subprocess.run(["openssl", "pkeyutl", "-encrypt", "-pubin",
  61. "-inkey", pubpem, "-pkeyopt", "rsa_padding_mode:pkcs1"],
  62. input=str(user_id).encode(), capture_output=True)
  63. if raw.returncode != 0:
  64. print("userId 加密失败:", raw.stderr.decode()); sys.exit(2)
  65. return base64.b64encode(raw.stdout).decode()
  66. if __name__ == "__main__":
  67. mode = sys.argv[1] if len(sys.argv) > 1 else "no-token"
  68. if mode == "no-token":
  69. print("=== 探测1:无 token 直连 GET /product/spu/page ===")
  70. print(call("GET", "/product/spu/page?pageNo=1&pageSize=20"))
  71. print("=== (若返回未登录/401,即证明必须先 identify 登录;带手机号重跑可查商品) ===")
  72. sys.exit(0)
  73. # 带手机号:完整链路
  74. mobile = mode
  75. print("=== 探测2:identify 登录(mobile 脱敏 %s****%s)===" % (mobile[:3], mobile[-4:]))
  76. login_raw = call("POST", "/member/user/identify", body={"mobile": mobile})
  77. print(login_raw)
  78. try:
  79. login = json.loads(login_raw.split("\n__HTTP__")[0])
  80. d = login.get("data") or {}
  81. token, uid = d.get("accessToken"), d.get("userId")
  82. except Exception as e:
  83. print("登录解析失败:", e); sys.exit(3)
  84. if not token:
  85. print("未拿到 accessToken,停止。"); sys.exit(3)
  86. print("\n=== 探测3:GET /product/spu/page(登录后)===")
  87. uid_enc = encrypt_uid(uid)
  88. spu_raw = call("GET", "/product/spu/page?pageNo=1&pageSize=50",
  89. token=token, uid_enc=uid_enc)
  90. print(spu_raw)
  91. try:
  92. spu = json.loads(spu_raw.split("\n__HTTP__")[0])
  93. lst = (spu.get("data") or {}).get("list") or []
  94. print("\n=== 商品清单汇总:共 %d 条 ===" % len(lst))
  95. for it in lst:
  96. print(" spuId=%s name=%s price=%s status=%s" % (
  97. it.get("id"), it.get("name"),
  98. (it.get("price") if isinstance(it.get("price"), str) else json.dumps(it.get("price"), ensure_ascii=False)),
  99. it.get("status")))
  100. except Exception as e:
  101. print("spu 解析失败:", e)