Files
37duAutomation/tools/goldenyun_login.py
T
puddy 1664821117 restore: 恢复 11-06~11-09 本地未提交改动
- libs: 新增 hr_sdk / hotel_report / dingtalk,更新 desktopauto
- controlplane-next: SDK 管理模块(controller/entity/migrations)与前端视图
- electron-shell: 插件同步、注册表、runner 调整
- plugins: XQ0035/XQ0041/XQ0042/XQ0045_XQ0046/XQ0048/XQ0076/XQ0078 等版本更新
- tests/tools: 新增 SDK 兼容性检查与打包工具(sdk_pack.py、sdk_compat_check.py)
2026-11-09 17:27:10 +08:00

258 lines
9.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""
金贵 GoldenSoft 微信端管理(vip6.wechat.goldenyun.cn/chqhpwq.web)接口登录探针
用途:验证「选门店 + 账号密码」能否通过 HTTP 接口登录,并顺带取一张报表页落盘分析。
形态:单文件自包含,无命令行参数,所有配置在本文件配置区内维护。
用法:
1) 填写下方【配置区】的 USERNAME / PASSWORD(门店不填默认取登录页第一个门店)
2) 用项目虚拟环境运行:
d:\\work\\code\\37duAutomation\\.venv\\Scripts\\python.exe tools\\goldenyun_login.py
说明:
- 登录失败(帐号密码错误)不会重试,避免触发平台累计失败锁定。
- 网络异常、服务端 5xx、结果未知才会重试,最多 3 次。
"""
import logging
import re
import sys
from datetime import datetime
from pathlib import Path
from urllib.parse import quote
import requests
# ==================== 配置区(改这里即可,无需命令行参数) ====================
BASE_URL = "http://vip6.wechat.goldenyun.cn"
APP_PATH = "/chqhpwq.web"
USERNAME = "37000864" # 登录账号,如 "zhangsan"
PASSWORD = "" # 登录密码
VPN_CODE = "" # 门店 GUID(优先级最高,留空则按下面名称/默认门店解析)
VPN_NAME = "金色湖畔石桥铺会馆" # 门店名称,如 "金色湖畔石桥铺会馆";留空 = 自动选登录页第一个门店
TARGET_PATH = "/wechat/memberreport/ticketconsumelist" # 登录后要访问的目标页(票券消费明细)
CHANNEL = "wechat" # wechat=微信端 / pad=平板端
TIMEOUT = 20 # 单请求超时(秒)
MAX_RETRY = 3 # 全局重试次数上限
DEBUG_DIR = Path(__file__).resolve().parent / "debug" # 调试 HTML 落盘目录
# ==========================================================================
LOGIN_PATH = "/login"
ERROR_HINTS = ("帐号密码错误", "账号密码错误", "用户名或密码", "密码错误", "已被锁定", "锁定",
"验证码", "无权")
logger = logging.getLogger("goldenyun-login")
def setup_logging() -> None:
for stream in (sys.stdout, sys.stderr):
try:
stream.reconfigure(encoding="utf-8") # type: ignore[attr-defined]
except Exception:
pass
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt="%H:%M:%S",
)
def new_session() -> requests.Session:
session = requests.Session()
session.headers.update({
"User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/120.0 Safari/537.36"),
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "zh-CN,zh;q=0.9",
"Referer": f"{BASE_URL}{APP_PATH}{LOGIN_PATH}",
})
return session
def fetch_login_page(session: requests.Session) -> str:
"""GET 登录页:拿 ASP.NET_SessionId,并解析可选门店列表。"""
url = f"{BASE_URL}{APP_PATH}{LOGIN_PATH}"
logger.info("获取登录页: %s", url)
resp = session.get(url, timeout=TIMEOUT)
resp.raise_for_status()
resp.encoding = "utf-8"
with_cookie = ", ".join(session.cookies.keys()) or "无"
logger.info("登录页状态=%s 长度=%s 会话Cookie=%s", resp.status_code, len(resp.text), with_cookie)
return resp.text
def parse_vpn_list(html: str) -> list:
"""解析门店列表:<li data-id="GUID" data-name="门店名">门店名</li>"""
block = html
start = html.find('class="vpn-list"')
if start != -1:
end = html.find("</ul>", start)
block = html[start:end if end != -1 else len(html)]
vpns = []
for match in re.finditer(r"<li([^>]*)>([^<]*)</li>", block):
attrs, text = match.group(1), match.group(2).strip()
code_match = re.search(r'data-id="([^"]+)"', attrs)
if not code_match:
continue
name_match = re.search(r'data-name="([^"]*)"', attrs)
name = (name_match.group(1) if name_match else text) or text
vpns.append({"code": code_match.group(1), "name": name.strip()})
return vpns
def pick_vpn(vpns: list) -> dict:
"""按配置选择门店:VPN_CODE 优先,其次 VPN_NAME 精确/包含匹配,最后取第一个。"""
if VPN_CODE:
for vpn in vpns:
if vpn["code"].lower() == VPN_CODE.strip().lower():
return vpn
logger.warning("配置的 VPN_CODE 未出现在门店列表中,直接使用配置值")
return {"code": VPN_CODE.strip(), "name": VPN_NAME.strip() or VPN_CODE.strip()}
if VPN_NAME:
keyword = VPN_NAME.strip()
for vpn in vpns:
if vpn["name"] == keyword:
return vpn
for vpn in vpns:
if keyword in vpn["name"] or vpn["name"] in keyword:
return vpn
logger.warning("未匹配到门店「%s」,回退第一个门店", keyword)
if not vpns:
raise RuntimeError("登录页未解析到任何门店,无法选择门店登录")
return vpns[0]
def build_login_url() -> str:
return f"{BASE_URL}{APP_PATH}{LOGIN_PATH}?returnurl={quote(APP_PATH + TARGET_PATH, safe='')}"
def extract_error(html: str) -> str:
"""从返回页里提取服务端错误提示。"""
for match in re.finditer(r'validation-summary-errors[^>]*>\s*<ul>(.*?)</ul>', html, re.S):
items = [re.sub(r"<[^>]+>", "", li).strip()
for li in re.findall(r"<li[^>]*>(.*?)</li>", match.group(1), re.S)]
items = [item for item in items if item]
if items:
return " / ".join(items)
for hint in ERROR_HINTS:
if hint in html:
return f"页面出现关键字「{hint}」"
return ""
def do_login(session: requests.Session, vpn: dict) -> requests.Response:
payload = {
"VpnCode": vpn["code"],
"VpnName": vpn["name"],
"UserName": USERNAME.strip(),
"Password": PASSWORD.strip(),
"Channel": CHANNEL,
}
url = build_login_url()
logger.info("提交登录: 门店=%s(%s) 账号=%s", vpn["name"], vpn["code"], payload["UserName"])
resp = session.post(url, data=payload, timeout=TIMEOUT, allow_redirects=True)
resp.encoding = "utf-8"
logger.info("登录响应: 状态=%s 最终URL=%s 长度=%s", resp.status_code, resp.url, len(resp.text))
return resp
def verify_logged_in(session: requests.Session) -> tuple:
"""访问目标报表页,判断会话是否已认证;返回 (是否成功, 响应文本)。"""
url = f"{BASE_URL}{APP_PATH}{TARGET_PATH}"
logger.info("验证会话: GET %s", url)
resp = session.get(url, timeout=TIMEOUT, allow_redirects=True)
resp.encoding = "utf-8"
logger.info("目标页响应: 状态=%s 最终URL=%s 长度=%s", resp.status_code, resp.url, len(resp.text))
landed_on_login = LOGIN_PATH in resp.url and "Password" in resp.text
return (resp.status_code == 200 and not landed_on_login), resp.text
def save_debug(name: str, content: str) -> Path:
DEBUG_DIR.mkdir(parents=True, exist_ok=True)
path = DEBUG_DIR / f"{datetime.now():%Y%m%d_%H%M%S}_{name}.html"
path.write_text(content, encoding="utf-8")
logger.info("已落盘: %s", path)
return path
def ensure_credentials() -> None:
global USERNAME, PASSWORD
if not USERNAME.strip():
USERNAME = input("请输入登录账号: ").strip()
if not PASSWORD:
import getpass
PASSWORD = getpass.getpass("请输入登录密码(输入不回显): ")
def run_once() -> tuple:
"""执行一次完整登录流程,返回 (结果, 说明):ok / bad_credential / unknown。"""
session = new_session()
html = fetch_login_page(session)
vpns = parse_vpn_list(html)
logger.info("解析到门店 %s 个: %s", len(vpns), [f'{v["name"]}' for v in vpns])
vpn = pick_vpn(vpns)
resp = do_login(session, vpn)
error = extract_error(resp.text)
if error:
save_debug("login_failed", resp.text)
return "bad_credential", f"服务端返回:{error}"
ok, page = verify_logged_in(session)
if ok:
save_debug("target_page", page)
return "ok", f"已进入目标页,Cookie: {', '.join(session.cookies.keys()) or '无'}"
save_debug("login_unknown", resp.text)
return "unknown", "登录页未返回错误提示,但目标页仍被重定向回登录页"
def main() -> int:
setup_logging()
ensure_credentials()
last_reason = ""
for attempt in range(1, MAX_RETRY + 1):
logger.info("===== 第 %s/%s 次尝试 =====", attempt, MAX_RETRY)
try:
result, reason = run_once()
except requests.RequestException as exc:
last_reason = f"网络异常: {exc}"
logger.warning(last_reason)
except Exception as exc: # noqa: BLE001
last_reason = f"执行异常: {exc}"
logger.warning(last_reason)
else:
if result == "ok":
logger.info("登录成功:%s", reason)
return 0
if result == "bad_credential":
# 凭据错误不重试,避免累计失败锁定账号
logger.error("登录失败:%s(不重试,避免账号锁定)", reason)
return 1
last_reason = reason
logger.warning("结果未知:%s", reason)
if attempt < MAX_RETRY:
logger.info("准备重试...")
logger.error("登录失败,已重试 %s 次:%s", MAX_RETRY, last_reason)
return 1
if __name__ == "__main__":
sys.exit(main())