feat: 增加从手机提取登录设备信息的工具
This commit is contained in:
@@ -0,0 +1,163 @@
|
||||
"""Read this phone's iCenter device identity over ADB and optionally update .env.
|
||||
|
||||
Connect the phone with USB debugging and root, then:
|
||||
|
||||
uv run --with cryptography python tools/extract_device.py
|
||||
uv run --with cryptography python tools/extract_device.py --write
|
||||
|
||||
It fills the login device fields: app id, device id, brand, model, Android ID,
|
||||
client IP when missing, and the installed version. Account, password, token and
|
||||
project id are left untouched.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
ENV_PATH = ROOT / ".env"
|
||||
PACKAGE = "com.zte.softda"
|
||||
APP_ID = "A00154"
|
||||
AID_FILE = (
|
||||
"/storage/emulated/0/Android/data/com.zte.softda/files/"
|
||||
".cn.com.zte.uac.config/aid_deviceid_gcm.cfg"
|
||||
)
|
||||
MMKV_DEVICE = "/data/data/com.zte.softda/files/mmkv/icenter_device_id"
|
||||
# Key embedded in libztencrypt.so and used by SecurityService.decrypt.
|
||||
AID_KEY = b"zmailzte12345678zmailzte12345678"
|
||||
|
||||
FIELDS = {
|
||||
"ICENTER_APP_ID": "app_id",
|
||||
"ICENTER_DEVICE_ID": "device_id",
|
||||
"ICENTER_DEVICE_NUM": "device_num",
|
||||
"ICENTER_DEVICE_BRAND": "brand",
|
||||
"ICENTER_DEVICE_MODE": "model",
|
||||
"ICENTER_DEVICE_NAME": "device_name",
|
||||
"ICENTER_ANDROID_ID": "android_id",
|
||||
"ICENTER_VERSION_NAME": "version_name",
|
||||
"ICENTER_VERSION_CODE": "version_code",
|
||||
}
|
||||
|
||||
|
||||
def adb(*args: str, binary: bool = False) -> str | bytes:
|
||||
proc = subprocess.run(["adb", *args], capture_output=True, check=False)
|
||||
if proc.returncode != 0:
|
||||
err = proc.stderr.decode("utf-8", "replace").strip()
|
||||
raise SystemExit(err or f"adb {' '.join(args)} 失败")
|
||||
return proc.stdout if binary else proc.stdout.decode("utf-8", "replace")
|
||||
|
||||
|
||||
def require_device() -> None:
|
||||
text = str(adb("devices"))
|
||||
serials = []
|
||||
for line in text.splitlines()[1:]:
|
||||
parts = line.split()
|
||||
if len(parts) >= 2 and parts[1] == "device":
|
||||
serials.append(parts[0])
|
||||
if not serials:
|
||||
raise SystemExit("没有已连接的 ADB 设备。请先打开 USB 调试并授权这台电脑。")
|
||||
if len(serials) > 1 and not os.environ.get("ANDROID_SERIAL"):
|
||||
raise SystemExit("连接了多台设备:" + ", ".join(serials) + "。请设置 ANDROID_SERIAL。")
|
||||
|
||||
|
||||
def su_cat(path: str) -> bytes:
|
||||
data = adb("exec-out", "su", "-c", f"cat {path}", binary=True)
|
||||
if not isinstance(data, bytes) or not data:
|
||||
raise SystemExit(f"读不到 {path}。需要 root,且 iCenter 至少打开过一次。")
|
||||
return data
|
||||
|
||||
|
||||
def decrypt_aid(secret_b64: str) -> str:
|
||||
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
||||
|
||||
raw = base64.b64decode(secret_b64.strip())
|
||||
if len(raw) <= 12:
|
||||
raise SystemExit("Android ID 文件内容太短,无法解密。")
|
||||
plain = AESGCM(AID_KEY).decrypt(raw[:12], raw[12:], None).decode("utf-8")
|
||||
if not re.fullmatch(r"[0-9a-fA-F-]{16,}", plain):
|
||||
raise SystemExit("Android ID 解密结果不像设备标识。")
|
||||
return plain
|
||||
|
||||
|
||||
def read_profile() -> dict[str, str]:
|
||||
require_device()
|
||||
pkg = str(adb("shell", "dumpsys", "package", PACKAGE))
|
||||
version_name = _first(r"versionName=(\S+)", pkg, "读不到 versionName")
|
||||
version_code = _first(r"versionCode=(\d+)", pkg, "读不到 versionCode")
|
||||
brand = str(adb("shell", "getprop", "ro.product.brand")).strip()
|
||||
model = str(adb("shell", "getprop", "ro.product.model")).strip()
|
||||
if not brand or not model:
|
||||
raise SystemExit("读不到手机品牌或型号。")
|
||||
|
||||
mmkv = su_cat(MMKV_DEVICE)
|
||||
slots = re.findall(rb"V02_[0-9A-F]+", mmkv)
|
||||
if not slots:
|
||||
raise SystemExit("没有在 icenter_device_id 里找到 V02 设备号。请先打开一次 iCenter。")
|
||||
device_ids = [item.decode("ascii") for item in slots]
|
||||
aid_blob = su_cat(AID_FILE).decode("utf-8", "replace")
|
||||
aid = "AID_" + decrypt_aid(aid_blob)
|
||||
parts = [device_ids[0]]
|
||||
if len(device_ids) > 1 and device_ids[1]:
|
||||
parts.append(device_ids[1])
|
||||
parts.append(aid)
|
||||
return {
|
||||
"app_id": APP_ID,
|
||||
"device_id": device_ids[0],
|
||||
"device_num": ";".join(parts),
|
||||
"brand": brand,
|
||||
"model": model,
|
||||
"device_name": f"{brand}-{model}",
|
||||
"android_id": aid,
|
||||
"version_name": version_name,
|
||||
"version_code": version_code,
|
||||
}
|
||||
|
||||
|
||||
def _first(pattern: str, text: str, error: str) -> str:
|
||||
match = re.search(pattern, text)
|
||||
if not match:
|
||||
raise SystemExit(error)
|
||||
return match.group(1)
|
||||
|
||||
|
||||
def update_env(profile: dict[str, str], env_path: Path = ENV_PATH) -> None:
|
||||
lines = env_path.read_text(encoding="utf-8").splitlines() if env_path.is_file() else []
|
||||
pending = {key: profile[name] for key, name in FIELDS.items()}
|
||||
out: list[str] = []
|
||||
for line in lines:
|
||||
stripped = line.strip()
|
||||
key = stripped.split("=", 1)[0] if stripped and not stripped.startswith("#") and "=" in stripped else ""
|
||||
if key in pending:
|
||||
out.append(f"{key}={pending.pop(key)}")
|
||||
else:
|
||||
out.append(line)
|
||||
if "ICENTER_CLIENT_IP" not in "\n".join(lines):
|
||||
pending["ICENTER_CLIENT_IP"] = "0.0.0.0"
|
||||
for key, value in pending.items():
|
||||
out.append(f"{key}={value}")
|
||||
env_path.write_text("\n".join(out) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="从手机提取 iCenter 登录所需的设备信息")
|
||||
parser.add_argument("--write", action="store_true", help="写回 .env 中的设备字段")
|
||||
args = parser.parse_args(argv)
|
||||
profile = read_profile()
|
||||
print(f"应用 {PACKAGE} {profile['version_name']} ({profile['version_code']})")
|
||||
print(f"设备 {profile['device_name']}")
|
||||
print(f"deviceId {profile['device_id']}")
|
||||
print(f"androidId {profile['android_id']}")
|
||||
print(f"deviceNum {profile['device_num']}")
|
||||
if args.write:
|
||||
update_env(profile)
|
||||
print(f"已写入 {ENV_PATH}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user