feat: 打卡记录拉取/缺卡统计工具(iEPMS token直连, 无需签名)

This commit is contained in:
2026-11-06 17:46:58 +08:00
parent 11c9b0b06f
commit 87af63a9c0
17 changed files with 988 additions and 0 deletions
+54
View File
@@ -0,0 +1,54 @@
"""mitmproxy addon: append every HTTP flow to a JSONL file.
Usage:
mitmdump -s tools/capture/dump_flows.py --set dump_path=data/captures/flows.jsonl
"""
import base64
import json
import os
import time
from mitmproxy import ctx, http
def _body(message: http.Message | None) -> dict | None:
if message is None:
return None
raw = message.get_content(strict=False) or b""
try:
return {"text": raw.decode("utf-8"), "size": len(raw)}
except UnicodeDecodeError:
return {"b64": base64.b64encode(raw).decode(), "size": len(raw)}
class DumpFlows:
def load(self, loader):
loader.add_option("dump_path", str, "data/captures/flows.jsonl", "JSONL output path")
def response(self, flow: http.HTTPFlow):
self._write(flow)
def error(self, flow: http.HTTPFlow):
self._write(flow)
def _write(self, flow: http.HTTPFlow):
req, resp = flow.request, flow.response
record = {
"ts": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(req.timestamp_start)),
"method": req.method,
"url": req.pretty_url,
"req_headers": list(req.headers.items(multi=True)),
"req_body": _body(req),
"status": resp.status_code if resp else None,
"resp_headers": list(resp.headers.items(multi=True)) if resp else None,
"resp_body": _body(resp),
"error": str(flow.error) if flow.error else None,
}
path = ctx.options.dump_path
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
with open(path, "a", encoding="utf-8") as f:
f.write(json.dumps(record, ensure_ascii=False) + "\n")
addons = [DumpFlows()]
+35
View File
@@ -0,0 +1,35 @@
#!/system/bin/sh
# Temporarily trust a CA system-wide on Android 14+ (APEX conscrypt store).
# Effective until reboot. Run as root: sh inject_ca.sh /data/local/tmp/<hash>.0
CERT="$1"
DIR=/data/local/tmp/cacerts
APEX=/apex/com.android.conscrypt/cacerts
[ -f "$CERT" ] || { echo "cert not found: $CERT"; exit 1; }
rm -rf "$DIR"
mkdir -p "$DIR"
cp "$APEX"/* "$DIR"/
cp "$CERT" "$DIR"/
chown -R root:root "$DIR"
chmod 755 "$DIR"
chmod 644 "$DIR"/*
chcon -R u:object_r:system_file:s0 "$DIR"
echo "certs prepared: $(ls "$DIR" | wc -l)"
bind_into() {
nsenter --mount=/proc/$1/ns/mnt -- /system/bin/mount --bind "$DIR" "$APEX" 2>/dev/null
}
ZYGOTES="$(pidof zygote) $(pidof zygote64)"
for Z in $ZYGOTES; do
bind_into "$Z" && echo "zygote $Z ok"
done
for Z in $ZYGOTES; do
for P in $(ps -o PID= -P "$Z"); do
bind_into "$P" &
done
done
wait
echo done
+50
View File
@@ -0,0 +1,50 @@
"""Print full details of captured flows by index.
Usage:
python tools/capture/show.py <index> [index ...] [--file flows.jsonl] [--max N]
"""
import argparse
import json
from pathlib import Path
def fmt_body(body: dict | None, limit: int) -> str:
if not body:
return "<empty>"
text = body.get("text")
if text is None:
return f"<binary {body['size']} bytes, b64>"
try:
text = json.dumps(json.loads(text), ensure_ascii=False, indent=2)
except ValueError:
pass
return text if len(text) <= limit else text[:limit] + f"\n... <{len(text) - limit} more chars>"
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("indexes", nargs="+", type=int)
ap.add_argument("--file", default="data/captures/flows.jsonl")
ap.add_argument("--max", type=int, default=4000)
args = ap.parse_args()
lines = Path(args.file).read_text(encoding="utf-8").splitlines()
for i in args.indexes:
r = json.loads(lines[i])
print(f"===== [{i}] {r['ts']} {r['method']} {r['url']}")
print("--- request headers")
for k, v in r["req_headers"]:
print(f"{k}: {v}")
print("--- request body")
print(fmt_body(r["req_body"], args.max))
print(f"--- response {r['status']} headers")
for k, v in r["resp_headers"] or []:
print(f"{k}: {v}")
print("--- response body")
print(fmt_body(r["resp_body"], args.max))
print()
if __name__ == "__main__":
main()
+26
View File
@@ -0,0 +1,26 @@
"""Print a one-line summary for each captured flow.
Usage:
python tools/capture/summarize.py [flows.jsonl] [keyword ...]
"""
import json
import sys
from pathlib import Path
def main() -> None:
args = sys.argv[1:]
path = Path(args[0]) if args and args[0].endswith(".jsonl") else Path("data/captures/flows.jsonl")
keywords = [a.lower() for a in args if not a.endswith(".jsonl")]
for i, line in enumerate(path.read_text(encoding="utf-8").splitlines()):
r = json.loads(line)
if keywords and not any(k in line.lower() for k in keywords):
continue
size = (r["resp_body"] or {}).get("size", 0)
print(f"{i:4d} {r['ts'][11:]} {r['method']:6s} {r['status']} {size:7d} {r['url'][:150]}")
if __name__ == "__main__":
main()
+81
View File
@@ -0,0 +1,81 @@
"""Extract the latest iEPMS auth token from captured traffic and update .env.
Why this exists: from-scratch pure-Python login is blocked by EMM device binding
("用户设备无效" / 100301). But the token (``X-Auth-Value``) is long-lived, and the
attendance read API does not enforce the request signature. So the practical refresh
path is: run the phone app through the capture proxy once, then grab the newest token
from the capture file here.
Usage:
python tools/extract_token.py # read default capture, print token
python tools/extract_token.py --write # also update ICENTER_TOKEN in .env
python tools/extract_token.py --captures path.jsonl
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
DEFAULT_CAPTURES = ROOT / "data" / "captures" / "flows.jsonl"
ENV_PATH = ROOT / ".env"
TOKEN_HEADER = "x-auth-value"
def latest_token(captures: Path) -> tuple[str, str] | None:
"""Return (token, ts) from the most recent flow carrying an auth token."""
best: tuple[str, str] | None = None
for line in captures.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line:
continue
try:
fl = json.loads(line)
except json.JSONDecodeError:
continue
for k, v in (fl.get("req_headers") or []):
if k.lower() == TOKEN_HEADER and v and len(v) >= 16:
ts = str(fl.get("ts") or "")
if best is None or ts > best[1]:
best = (v, ts)
return best
def update_env(token: str, env_path: Path = ENV_PATH) -> None:
lines = env_path.read_text(encoding="utf-8").splitlines() if env_path.is_file() else []
out, found = [], False
for ln in lines:
if ln.strip().startswith("ICENTER_TOKEN="):
out.append(f"ICENTER_TOKEN={token}")
found = True
else:
out.append(ln)
if not found:
out.append(f"ICENTER_TOKEN={token}")
env_path.write_text("\n".join(out) + "\n", encoding="utf-8")
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description="提取最新 iEPMS token")
ap.add_argument("--captures", default=str(DEFAULT_CAPTURES))
ap.add_argument("--write", action="store_true", help="写入 .env 的 ICENTER_TOKEN")
args = ap.parse_args(argv)
cap = Path(args.captures)
if not cap.is_file():
raise SystemExit(f"找不到抓包文件: {cap}")
res = latest_token(cap)
if not res:
raise SystemExit("未在抓包中找到 x-auth-value token。请先让手机 App 走代理发一次请求。")
token, ts = res
print(f"最新 token: {token} (ts={ts})")
if args.write:
update_env(token)
print(f"已写入 {ENV_PATH}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+97
View File
@@ -0,0 +1,97 @@
"""Small adb helpers for driving the phone during capture.
Usage:
python tools/phone.py shot [out.png] # screenshot
python tools/phone.py texts # list visible texts with centers
python tools/phone.py tap <text> # tap first node whose text/desc contains <text>
python tools/phone.py tapxy <x> <y>
python tools/phone.py back
python tools/phone.py bind # bind CA dir into every app process
"""
import re
import subprocess
import sys
import tempfile
import xml.etree.ElementTree as ET
from pathlib import Path
PKG = "com.zte.softda"
def adb(*args: str, binary: bool = False):
out = subprocess.run(["adb", *args], capture_output=True, check=False)
return out.stdout if binary else out.stdout.decode("utf-8", "replace")
def su(cmd: str) -> str:
return adb("shell", f"su -c '{cmd}'")
def shot(path: str = "data/screen.png") -> None:
adb("shell", "screencap -p /data/local/tmp/s.png")
adb("pull", "/data/local/tmp/s.png", path)
print(path)
def nodes():
adb("shell", "uiautomator dump /data/local/tmp/ui.xml")
xml = adb("shell", "cat /data/local/tmp/ui.xml")
root = ET.fromstring(xml[xml.index("<"):])
for n in root.iter("node"):
label = n.get("text") or n.get("content-desc") or ""
m = re.findall(r"\d+", n.get("bounds", ""))
if label and len(m) == 4:
x1, y1, x2, y2 = map(int, m)
yield label, (x1 + x2) // 2, (y1 + y2) // 2
def texts() -> None:
for label, x, y in nodes():
print(f"{x:5d} {y:5d} {label}")
def tap(text: str) -> None:
for label, x, y in nodes():
if text in label:
adb("shell", "input", "tap", str(x), str(y))
print(f"tap {label!r} at {x},{y}")
return
print(f"not found: {text}")
sys.exit(1)
BIND_SCRIPT = f"""\
for P in $(ps -A -o PID,NAME | awk '$2 ~ /^{PKG}/ {{print $1}}'); do
grep -q conscrypt/cacerts /proc/$P/mountinfo && continue
nsenter --mount=/proc/$P/ns/mnt -- /system/bin/mount --bind \\
/data/local/tmp/cacerts /apex/com.android.conscrypt/cacerts && echo "bound $P"
done
"""
def bind() -> None:
local = Path(tempfile.gettempdir()) / "bindall.sh"
local.write_bytes(BIND_SCRIPT.encode())
adb("push", str(local), "/data/local/tmp/bindall.sh")
print(su("sh /data/local/tmp/bindall.sh").strip() or "all processes already bound")
def main() -> None:
cmd, *rest = sys.argv[1:] or ["texts"]
if cmd == "shot":
shot(*rest)
elif cmd == "texts":
texts()
elif cmd == "tap":
tap(" ".join(rest))
elif cmd == "tapxy":
adb("shell", "input", "tap", *rest)
elif cmd == "back":
adb("shell", "input", "keyevent", "4")
elif cmd == "bind":
bind()
if __name__ == "__main__":
main()