# -*- coding: utf-8 -*- """Copy dy_cookie from dylive VPS DB → physical guest. Cookie is mandatory for Douyin probes.""" from __future__ import annotations import json import sys import time import paramiko sys.stdout.reconfigure(encoding="utf-8", errors="replace") PASS_GUEST = "4669805" def ssh(host, port, user, pw, tries=8): last = None for i in range(tries): try: c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) c.connect( host, port, user, pw, timeout=60, banner_timeout=120, allow_agent=False, look_for_keys=False, ) return c except Exception as ex: last = ex print(f"ssh try{i} {type(ex).__name__}: {ex}", flush=True) time.sleep(2 + i) raise last # type: ignore[misc] def run(c, cmd, t=120): _, o, e = c.exec_command(cmd, timeout=t) return (o.read() + e.read()).decode("utf-8", "replace") DUMP = r''' import json, sqlite3 from pathlib import Path p = Path("/opt/douyinWEB/backend/data/monitor.db") con = sqlite3.connect(f"file:{p}?mode=ro", uri=True) con.row_factory = sqlite3.Row out = {} for k in ("dy_cookie", "dy_cookie_updated_at", "http_proxy"): row = con.execute("SELECT value FROM kv_settings WHERE key=?", (k,)).fetchone() out[k] = row["value"] if row else None # also legacy names for k in ("cookie", "douyin_cookie"): row = con.execute("SELECT value FROM kv_settings WHERE key=?", (k,)).fetchone() if row: out[k] = row["value"] con.close() # summarize without dumping full secret to stdout logs beyond length cookie_raw = out.get("dy_cookie") cookie = "" if cookie_raw is not None: try: cookie = json.loads(cookie_raw) if isinstance(cookie_raw, str) and cookie_raw[:1] in "\"[{" else cookie_raw except Exception: cookie = cookie_raw if not isinstance(cookie, str): cookie = str(cookie or "") print(json.dumps({ "dy_cookie_len": len(cookie or ""), "dy_cookie_prefix": (cookie or "")[:24], "dy_cookie_updated_at": out.get("dy_cookie_updated_at"), "has_legacy_cookie": bool(out.get("cookie") or out.get("douyin_cookie")), "payload": out, }, ensure_ascii=False)) ''' APPLY = r''' import json, sqlite3, time, sys from pathlib import Path payload = json.loads(Path("/tmp/_dy_cookie_payload.json").read_text(encoding="utf-8")) raw = payload.get("dy_cookie") # value in kv is JSON-encoded string if raw is None: raise SystemExit("no dy_cookie in payload") # normalize to JSON string stored in kv_settings try: parsed = json.loads(raw) if isinstance(raw, str) and raw[:1] == '"' else raw except Exception: parsed = raw if not isinstance(parsed, str): parsed = str(parsed or "") parsed = parsed.strip() if len(parsed) < 20: raise SystemExit(f"dy_cookie too short len={len(parsed)}") store = json.dumps(parsed, ensure_ascii=False) updated = payload.get("dy_cookie_updated_at") if not updated: updated = json.dumps(time.time()) elif isinstance(updated, (int, float)): updated = json.dumps(float(updated)) else: # already json text or number text try: json.loads(updated) except Exception: updated = json.dumps(time.time()) dbp = Path("/opt/douyinWEB/backend/data/monitor.db") # backup bak = dbp.with_suffix(dbp.suffix + f".bak-cookie-{int(time.time())}") import shutil shutil.copy2(dbp, bak) con = sqlite3.connect(str(dbp)) before = con.execute("SELECT value FROM kv_settings WHERE key='dy_cookie'").fetchone() before_len = 0 if before: try: before_len = len(json.loads(before[0]) or "") except Exception: before_len = len(before[0] or "") for k, v in (("dy_cookie", store), ("dy_cookie_updated_at", updated)): ex = con.execute("SELECT key FROM kv_settings WHERE key=?", (k,)).fetchone() if ex: con.execute("UPDATE kv_settings SET value=? WHERE key=?", (v, k)) else: con.execute("INSERT INTO kv_settings(key, value) VALUES (?,?)", (k, v)) # clear risk pause if stored for k in ("risk_paused_until", "global_risk_paused_until"): con.execute("DELETE FROM kv_settings WHERE key=?", (k,)) con.commit() after = json.loads(con.execute("SELECT value FROM kv_settings WHERE key='dy_cookie'").fetchone()[0]) con.close() print(json.dumps({ "ok": True, "bak": str(bak), "before_len": before_len, "after_len": len(after or ""), "prefix": (after or "")[:24], }, ensure_ascii=False)) ''' def main(): print("=== dump dy_cookie from dylive ===", flush=True) v = ssh("107.173.30.245", 22, "root", "Xiao4669805") sftp = v.open_sftp() with sftp.file("/tmp/_dump_dy_cookie.py", "w") as f: f.write(DUMP) sftp.close() out = run(v, "python3 /tmp/_dump_dy_cookie.py", 60) line = [ln for ln in out.splitlines() if ln.strip().startswith("{")] if not line: print("DUMP FAIL", out[:2000], flush=True) raise SystemExit(1) meta = json.loads(line[-1]) print( f"dylive cookie len={meta.get('dy_cookie_len')} prefix={meta.get('dy_cookie_prefix')!r}", flush=True, ) if int(meta.get("dy_cookie_len") or 0) < 20: print("dylive cookie empty/too short — abort", flush=True) raise SystemExit(2) payload = meta["payload"] v.close() print("=== apply to physical ===", flush=True) g = ssh("107.173.30.245", 4014, "eric", PASS_GUEST) sftp = g.open_sftp() with sftp.file("/tmp/_dy_cookie_payload.json", "w") as f: f.write(json.dumps(payload, ensure_ascii=False)) with sftp.file("/tmp/_apply_dy_cookie.py", "w") as f: f.write(APPLY) sftp.close() applied = run( g, f"echo '{PASS_GUEST}' | sudo -S -p '' /opt/douyinWEB/backend/.venv/bin/python /tmp/_apply_dy_cookie.py", 60, ) print(applied, flush=True) if '"ok": true' not in applied.replace("True", "true") and '"ok":true' not in applied.replace(" ", ""): # python json uses true if '"ok": true' not in applied and '"ok":true' not in applied: # check for ok True from print of dict - we use json.dumps so true if '"ok": true' not in applied and not ('"ok":true' in applied.replace(" ", "")): if '"after_len"' not in applied: raise SystemExit(f"apply failed: {applied[:1500]}") # clear in-memory risk pause via API if possible, else restart api print("=== restart api to reload settings ===", flush=True) print( run( g, f"echo '{PASS_GUEST}' | sudo -S -p '' bash -lc '" "systemctl restart douyinweb-api; sleep 4; systemctl is-active douyinweb-api; " "python3 - <<\"PY\"\n" "import sqlite3,json\n" "c=sqlite3.connect(\"/opt/douyinWEB/backend/data/monitor.db\")\n" "v=c.execute(\"select value from kv_settings where key=\\\"dy_cookie\\\"\").fetchone()[0]\n" "print(\"verify_len\", len(json.loads(v)))\n" "PY\n" "'", 90, ), flush=True, ) g.close() print("DONE cookie restored from dylive → physical", flush=True) if __name__ == "__main__": main()