"""登录中兴 e 学并打印当前用户资料。 账号从环境变量 EUNIV_LOGIN、EUNIV_PASSWORD 读取,不写入文件。 """ from __future__ import annotations import base64 import io import os import random import sys import time import uuid from urllib.parse import quote import httpx from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import padding from PIL import Image PORTAL = "https://bmtucportal.zte.com.cn" EUNIV = "https://euniv.zte.com.cn" YXT_API = "https://api-qidacustomc1.yunxuetang.cn" REDIRECT_URI = f"{YXT_API}/v1/ztctech/sso" CLIENT_ID = "30051" TENANT_ID = "10001" APP_ID = "10051" USER_AGENT = ( "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:158.0) " "Gecko/20100101 Firefox/158.0" ) def now_ms() -> int: return int(time.time() * 1000) def make_kid(prefix: str = "t") -> str: return prefix + "".join(random.choice("1234567890") for _ in range(4)) def encrypt_password(public_key_b64: str, password: str) -> str: key = serialization.load_der_public_key(base64.b64decode(public_key_b64)) cipher = key.encrypt(password.encode("utf-8"), padding.PKCS1v15()) return base64.b64encode(cipher).decode("ascii") def decode_data_uri(value: str) -> bytes: payload = value.split(",", 1)[1] if "," in value else value return base64.b64decode(payload) def jigsaw_offset(big_png: bytes, small_png: bytes, top: int) -> int: """返回滑块左边缘在底图上的横坐标。样本上与抓包提交值一致。""" big = Image.open(io.BytesIO(big_png)).convert("RGBA") small = Image.open(io.BytesIO(small_png)).convert("RGBA") width, height = big.size piece_w, piece_h = small.size mask: list[tuple[int, int, tuple[int, int, int]]] = [] for y in range(piece_h): for x in range(piece_w): red, green, blue, alpha = small.getpixel((x, y)) if alpha > 128: mask.append((x, y, (red, green, blue))) best_x = 0 best_score = None limit = width - piece_w for origin in range(max(limit, 0)): score = 0 for x, y, color in mask: pixel = big.getpixel((origin + x, top + y)) score += abs(pixel[0] - color[0]) + abs(pixel[1] - color[1]) + abs(pixel[2] - color[2]) if best_score is None or score < best_score: best_score = score best_x = origin if top + piece_h > height: raise RuntimeError("拼图纵坐标超出底图高度") return best_x class EunivLogin: def __init__(self, login_name: str, password: str) -> None: self.login_name = login_name.strip() self.password = password self.client = httpx.Client(timeout=30, follow_redirects=True, headers={"User-Agent": USER_AGENT}) def close(self) -> None: self.client.close() def portal_headers(self) -> dict[str, str]: referer = ( f"{PORTAL}/uc/{TENANT_ID}/oauthLogin?client_id={CLIENT_ID}" f"&scope=profile&redirect_uri={quote(REDIRECT_URI, safe='')}" "&response_type=code" ) return { "Accept": "application/json, text/plain, */*", "Content-Type": "application/json;charset=UTF-8", "Origin": PORTAL, "Referer": referer, "X-App-Id": APP_ID, "X-Device-Type": "pc", "X-Itp-Value": "from=ucs-portal;client=pc;platform=portal", "X-Lang-Id": "zh_CN", "X-Tenant-Id": TENANT_ID, "x_uuid": str(uuid.uuid4()), } def code_of(self, payload: dict) -> tuple[str, str, object]: block = payload.get("code") or {} return block.get("code") or "", block.get("msg") or "", payload.get("bo") def login(self) -> dict: self.client.get(EUNIV + "/") self.client.post( f"{PORTAL}/zte-bmt-ucs-portalbff/oauth/validate", headers=self.portal_headers(), json={ "clientId": CLIENT_ID, "redirectUri": REDIRECT_URI, "responseType": "code", "scope": "profile", "_t": now_ms(), }, ) key_resp = self.client.post( f"{PORTAL}/zte-bmt-ucs-portalbff/srv/password/publicKey/{TENANT_ID}", headers=self.portal_headers(), json={"_t": now_ms()}, ) key_code, key_message, public_key = self.code_of(key_resp.json()) if key_code != "0000" or not isinstance(public_key, str): raise RuntimeError(f"获取密码公钥失败:{key_message or key_resp.status_code}") check_resp = self.client.post( f"{PORTAL}/zte-bmt-ucs-portalbff/srv/pas/securitycode/check", headers=self.portal_headers(), json={"accountId": self.login_name, "callerId": APP_ID, "_t": now_ms()}, ) check_code, check_message, needs_security_code = self.code_of(check_resp.json()) if check_code == "0000" and needs_security_code is True: raise RuntimeError("这个账号开启了动态安全码,当前登录流程还不能提交安全码") if check_code not in ("", "0000"): raise RuntimeError(f"安全码检查失败:{check_message}") cipher = encrypt_password(public_key, self.password) last_message = "登录未完成" for _ in range(3): kid = make_kid("t") image_resp = self.client.get( f"{PORTAL}/zte-bmt-ucs-portalbff/srv/kaptcha/jigsaw", params={"kid": kid, "_t": now_ms()}, headers=self.portal_headers(), ) image_code, image_message, image = self.code_of(image_resp.json()) if image_code != "0000": raise RuntimeError(f"获取拼图失败:{image_message}") offset = jigsaw_offset( decode_data_uri(image["bigImg"]), decode_data_uri(image["smallImg"]), int(image["yHeight"]), ) headers = self.portal_headers() headers.update({"kcode": "", "kid": make_kid(""), "kskip": "true", "source": APP_ID}) login_resp = self.client.post( f"{PORTAL}/zte-bmt-ucs-portalbff/srv/login", headers=headers, json={ "loginName": self.login_name, "password": cipher, "kid": kid, "jigsawCode": offset, "_t": now_ms(), }, ) login_code, last_message, profile = self.code_of(login_resp.json()) if login_code == "0000": return profile if any(word in last_message for word in ("验证码", "拼图", "滑块")): continue raise RuntimeError(f"登录失败:{last_message}") raise RuntimeError(f"登录失败:{last_message}") def authorize(self, profile: dict) -> None: account_id = str(profile["accountId"]) user_id = str(profile["userId"]) token = str(profile["token"]) domain = "zte.com.cn" jar = { "UCSLoginName": account_id, "UCSSSOAccount": account_id, "UCSSSOUser": user_id, "UCSSSOToken": token, "UCSSSOInfo": str(profile.get("ssoinfo") or ""), "UCSSSOLanguage": "zh_CN", "UCSLoginTime": str(now_ms()), "iAuthTenantId_prod": TENANT_ID, "iAuthUserId_prod": user_id, "iAuthUid_prod": account_id, "iAuthTid_prod": token, "iAuthLanguage_prod": "zh_CN", } if profile.get("unionId"): jar["iuacUnionId"] = str(profile["unionId"]) for name, value in jar.items(): self.client.cookies.set(name, value, domain=domain, path="/") response = self.client.post( f"{PORTAL}/zte-bmt-ucs-portalbff/oauth/authorize", params={ "redirect_uri": REDIRECT_URI, "client_id": CLIENT_ID, "response_type": "code", "scope": "profile", }, headers=self.portal_headers(), json={"accountId": account_id, "token": token, "userId": user_id, "_t": now_ms()}, ) code, message, redirect_url = self.code_of(response.json()) if code != "0000" or not isinstance(redirect_url, str): raise RuntimeError(f"申请学习平台授权码失败:{message}") self.client.get(redirect_url, headers={"Referer": PORTAL + "/", "User-Agent": USER_AGENT}) def user_info(self) -> dict: token = None for cookie in self.client.cookies.jar: if cookie.name == "ELEARNING_00024" and cookie.value: token = cookie.value break if not token: names = sorted({cookie.name for cookie in self.client.cookies.jar}) raise RuntimeError("学习平台没有返回登录会话,现有 Cookie 名称:" + ", ".join(names)) response = self.client.post( f"{YXT_API}/v1/customdiy/user/getuserinfobyid", content=b"", headers={ "Accept": "application/json, text/plain, */*", "Content-Type": "application/json", "Origin": EUNIV, "Referer": EUNIV + "/", "source": "501", "token": token, "User-Agent": USER_AGENT, }, ) response.raise_for_status() payload = response.json() if not isinstance(payload, dict) or "cnName" not in payload: raise RuntimeError("用户信息返回无法识别") return payload def main() -> int: login_name = os.environ.get("EUNIV_LOGIN", "").strip() password = os.environ.get("EUNIV_PASSWORD", "") if not login_name or not password: print("请设置环境变量 EUNIV_LOGIN 和 EUNIV_PASSWORD", file=sys.stderr) return 2 client = EunivLogin(login_name, password) try: profile = client.login() client.authorize(profile) info = client.user_info() finally: client.close() fields = [ ("工号", info.get("username")), ("姓名", info.get("cnName")), ("部门", info.get("departmentName")), ("岗位层级", info.get("userClassLevelName")), ("邮箱", info.get("email")), ] print("登录成功") for label, value in fields: if value: print(f"{label}:{value}") return 0 if __name__ == "__main__": try: raise SystemExit(main()) except Exception as exc: print(str(exc), file=sys.stderr) raise SystemExit(1)