douyinWEB/scripts/_sync_server_default_admins.py
eric d409e416da Ship physical dual-edge stack, Studio CDP live metrics, and ops tooling.
Capture Neko/WG/network hubs, Studio viewer charts, physical deploy docs, and one-shot scripts so VPS vs physical can be toggled later without losing WIP.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 22:42:40 -05:00

209 lines
6.7 KiB
Python

# -*- coding: utf-8 -*-
"""Sync default admin hackrobot / Xiao4669805@ across all self-deployed projects on server."""
from __future__ import annotations
import re
import time
from pathlib import Path
import paramiko
HOST = "107.173.30.245"
REPO = "/opt/douyinWEB"
LOCAL = Path(r"C:/Users/admin/Desktop/douyinWEB")
USER = "hackrobot"
PASSWORD = "Xiao4669805@"
PB_UPSERTS: list[tuple[str, str, str]] = [
("/opt/pocketbase/pocketbase", "/opt/douyinWEB/pb/pb_data", "hackrobot@douyin.local"),
("/opt/pocketbase/pocketbase", "/opt/wauto/pocketbase/pb_data", "hackrobot@wx.nomadro.com"),
("/opt/tiktokWEB/pocketbase/pocketbase", "/opt/tiktokWEB/pocketbase/pb_data", "hackrobot@nomadro.live"),
("/opt/xauto/pocketbase/pocketbase", "/opt/xauto/pocketbase/pb_data", "hackrobot@xauto.local"),
("/opt/robook/pocketbase/pocketbase", "/opt/robook/pocketbase/pb_data", "hackrobot@book.nomadro.com"),
("/opt/pocketbase/pocketbase", "/opt/pocketbase/pb_data", "hackrobot@nomadro.com"),
]
ENV_PATCHES: dict[str, dict[str, str]] = {
"/opt/tiktokWEB/.env": {
"POCKETBASE_ADMIN_EMAIL": "hackrobot@nomadro.live",
"POCKETBASE_ADMIN_PASSWORD": PASSWORD,
},
"/opt/xauto/.env": {
"POCKETBASE_ADMIN_EMAIL": "hackrobot@xauto.local",
"POCKETBASE_ADMIN_PASSWORD": PASSWORD,
},
"/opt/robook/.env": {
"POCKETBASE_ADMIN_EMAIL": "hackrobot@book.nomadro.com",
"POCKETBASE_ADMIN_PASSWORD": PASSWORD,
"ADMIN_USERNAME": USER,
"ADMIN_PASSWORD": PASSWORD,
},
"/etc/nomadro/umami.env": {
"UMAMI_USER": USER,
"UMAMI_PASSWORD": PASSWORD,
},
"/etc/nomadro/ntfy.env": {
"NTFY_USER": USER,
"NTFY_PASSWORD": PASSWORD,
"NTFY_TOPIC": "dylive",
},
}
DY_FILES = [
"backend/app/config.py",
"backend/app/session_auth.py",
"backend/app/main.py",
]
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, "root", "Xiao4669805", timeout=30, allow_agent=False, look_for_keys=False)
def run(cmd: str, timeout: int = 240) -> str:
_, o, e = c.exec_command(cmd, timeout=timeout)
out = o.read().decode("utf-8", "replace").strip()
err = e.read().decode("utf-8", "replace").strip()
return (out + ("\n" + err if err else "")).strip()
def patch_env(remote_path: str, updates: dict[str, str]) -> None:
content = run(f"test -f {remote_path} && cat {remote_path} || echo ''")
lines = content.splitlines()
seen = set()
out: list[str] = []
for line in lines:
if not line.strip() or line.strip().startswith("#") or "=" not in line:
out.append(line)
continue
key = line.split("=", 1)[0].strip()
if key in updates:
out.append(f"{key}={updates[key]}")
seen.add(key)
else:
out.append(line)
for key, val in updates.items():
if key not in seen:
out.append(f"{key}={val}")
body = "\n".join(out).rstrip() + "\n"
tmp = f"/tmp/envpatch_{int(time.time())}_{Path(remote_path).name}"
sftp = c.open_sftp()
with sftp.file(tmp, "w") as f:
f.write(body)
sftp.close()
run(f"install -m 600 {tmp} {remote_path} && rm -f {tmp}")
ts = int(time.time())
print("[backup db]", run(f"cp -a {REPO}/backend/data/monitor.db /tmp/monitor.db.bak_admin_all_{ts}"))
print("[upload douyinWEB auth files]")
sftp = c.open_sftp()
for rel in DY_FILES:
sftp.put(str(LOCAL / rel), f"{REPO}/{rel.replace(chr(92), '/')}")
sftp.close()
print("[douyinWEB systemd admin env]")
admin_dropin = f"""[Service]
Environment=DY_ADMIN_USERNAME={USER}
Environment=DY_ADMIN_PASSWORD={PASSWORD}
Environment=DY_PB_ADMIN_EMAIL=hackrobot@douyin.local
Environment=DY_PB_ADMIN_PASSWORD={PASSWORD}
"""
tmp_dropin = f"/tmp/douyinweb-admin-{ts}.conf"
sftp = c.open_sftp()
with sftp.file(tmp_dropin, "w") as f:
f.write(admin_dropin)
sftp.close()
run(
f"install -d /etc/systemd/system/douyinweb-api.service.d && "
f"install -m 644 {tmp_dropin} /etc/systemd/system/douyinweb-api.service.d/admin.conf && "
f"rm -f {tmp_dropin} && systemctl daemon-reload"
)
print("[douyinWEB pb binary symlink]")
run(
f"test -x {REPO}/pb/pocketbase || ln -sf /opt/pocketbase/pocketbase {REPO}/pb/pocketbase"
)
print("[patch env files]")
for path, updates in ENV_PATCHES.items():
print(" ", path)
patch_env(path, updates)
print("[sync douyinWEB site admin hash]")
print(
run(
f"cd {REPO}/backend && .venv/bin/python -c \""
"from app.session_auth import ensure_default_admin_credentials, get_admin_credentials; "
"ensure_default_admin_credentials(); u,h=get_admin_credentials(); "
"print('douyinWEB site admin', u, h[:12])\""
)
)
print("[pocketbase superusers]")
for bin_path, data_dir, email in PB_UPSERTS:
cmd = (
f"test -x {bin_path} && {bin_path} superuser upsert {email} '{PASSWORD}' "
f"--dir={data_dir} 2>&1 || echo SKIP:{email}"
)
print(f" {email} ->", run(cmd))
print("[umami admin user]")
bcrypt_hash = run(
f"python3 -c \"import bcrypt; print(bcrypt.hashpw(b'{PASSWORD}', bcrypt.gensalt(rounds=10)).decode())\""
)
bcrypt_hash = bcrypt_hash.strip().splitlines()[-1]
umami_sql = (
f"UPDATE \"user\" SET username = '{USER}', password = '{bcrypt_hash}', updated_at = now() "
f"WHERE username IN ('admin', '{USER}');\n"
)
umami_sql_path = f"/tmp/umami_admin_{ts}.sql"
sftp = c.open_sftp()
with sftp.file(umami_sql_path, "w") as f:
f.write(umami_sql)
sftp.close()
print(run(f"docker cp {umami_sql_path} umami-db-1:/tmp/umami_admin.sql && "
f"docker exec umami-db-1 psql -U umami -d umami -f /tmp/umami_admin.sql 2>&1"))
print("[ntfy admin user]")
print(
run(
f"docker exec -e NTFY_PASSWORD='{PASSWORD}' ntfy-ntfy-1 ntfy user add --role=admin {USER} 2>&1 || "
f"docker exec -e NTFY_PASSWORD='{PASSWORD}' ntfy-ntfy-1 ntfy user change-pass {USER} 2>&1"
)
)
print("[restart services]")
services = [
"douyinweb-api",
"douyinweb-pb",
"tiktok-promo-backend",
"xauto-web",
"hackrobot-pb",
"umami-umami-1",
]
for svc in services:
if svc.endswith("-1"):
print(f" restart {svc}", run(f"docker restart {svc} 2>&1 | tail -1"))
else:
print(f" restart {svc}", run(f"systemctl restart {svc}; sleep 2; systemctl is-active {svc}"))
print("[login test dylive]")
print(
run(
"curl -s -o /dev/null -w '%{http_code}' -X POST http://127.0.0.1:8014/api/auth/login "
f"-H 'Content-Type: application/json' -d '{{\"username\":\"{USER}\",\"password\":\"{PASSWORD}\"}}'"
)
)
print("[umami users]")
print(run('docker exec umami-db-1 psql -U umami -d umami -c "select username, role from \"user\";" 2>&1'))
print("[ntfy users]")
print(run("docker exec ntfy-ntfy-1 ntfy user list 2>&1"))
c.close()
print("DONE")