84 lines
2.8 KiB
Python
84 lines
2.8 KiB
Python
"""
|
|
小米账号登录 - 通过浏览器获取 serviceToken
|
|
浏览器打开后请手动登录,脚本会自动检测登录成功
|
|
"""
|
|
|
|
import json
|
|
import time
|
|
from playwright.sync_api import sync_playwright
|
|
|
|
XIAOI_CONFIG = "xiaomi_config.json"
|
|
|
|
|
|
def login_and_get_tokens():
|
|
print("启动浏览器,请登录小米账号...")
|
|
with sync_playwright() as p:
|
|
browser = p.chromium.launch(headless=False, args=["--start-maximized"])
|
|
context = browser.new_context(no_viewport=True)
|
|
page = context.new_page()
|
|
|
|
page.goto("https://account.xiaomi.com/pass/serviceLogin?sid=micoapi&_json=true&callback=https%3A%2F%2Fapi2.mina.mi.com%2Fsts")
|
|
page.wait_for_load_state("networkidle")
|
|
|
|
print("请在浏览器中完成登录(输入手机号、密码、验证码)")
|
|
print("等待登录完成(最长5分钟)...")
|
|
|
|
# 等待页面离开登录页(说明登录成功)
|
|
try:
|
|
page.wait_for_url(lambda url: "account.xiaomi.com/pass" not in url, timeout=300_000)
|
|
print("检测到登录成功!")
|
|
except Exception:
|
|
print("登录超时或失败")
|
|
browser.close()
|
|
return None
|
|
|
|
time.sleep(3)
|
|
|
|
# 获取 cookies
|
|
cookies = context.cookies()
|
|
cookie_dict = {c["name"]: c["value"] for c in cookies}
|
|
|
|
service_token = cookie_dict.get("serviceToken", "")
|
|
user_id = cookie_dict.get("userId", "")
|
|
|
|
print(f"获取到 {len(cookies)} 个 cookies")
|
|
print(f" userId: {user_id}")
|
|
print(f" serviceToken: {'有' if service_token else '无'}")
|
|
|
|
# 通过浏览器调用 device_list API
|
|
print("\n获取设备列表...")
|
|
result = page.evaluate("""
|
|
async () => {
|
|
const resp = await fetch('https://api2.mina.mi.com/admin/v2/device_list?master=0&requestId=app_ios_' + Math.random().toString(36).substr(2, 30));
|
|
return await resp.json();
|
|
}
|
|
""")
|
|
|
|
devices = []
|
|
if result.get("code") == 0:
|
|
devices = result.get("data", [])
|
|
print(f"找到 {len(devices)} 个设备:")
|
|
for d in devices:
|
|
print(f" 名称: {d.get('name')} | 型号: {d.get('hardware')} | DID: {d.get('deviceID')}")
|
|
else:
|
|
print(f"获取设备失败: {result}")
|
|
|
|
# 保存配置
|
|
config = {
|
|
"userId": user_id,
|
|
"serviceToken": service_token,
|
|
"devices": devices,
|
|
"allCookies": cookie_dict,
|
|
}
|
|
|
|
with open(XIAOI_CONFIG, "w", encoding="utf-8") as f:
|
|
json.dump(config, f, ensure_ascii=False, indent=2)
|
|
|
|
print(f"\n配置已保存到 {XIAOI_CONFIG}")
|
|
browser.close()
|
|
return config
|
|
|
|
|
|
if __name__ == "__main__":
|
|
login_and_get_tokens()
|