import paramiko, time, sys, base64, io, tarfile NAS_HOST = "100.85.152.112" NAS_PORT = 22 NAS_USER = "simon" NAS_PASS = "Nas82829330" NAS_DEPLOY_PATH = "/volume1/docker/gaokao-portal" DOCKER = f"echo '{NAS_PASS}' | sudo -S /usr/local/bin/docker" SUDO_DOCKER = f"{DOCKER}" def connect(): c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) c.connect(NAS_HOST, NAS_PORT, NAS_USER, NAS_PASS, timeout=15) return c def run(c, cmd, desc="", timeout=30): if desc: print(f"[{desc}]") stdin, stdout, stderr = c.exec_command(cmd, timeout=timeout) out = stdout.read().decode("utf-8", errors="replace").strip() err = stderr.read().decode("utf-8", errors="replace").strip() status = stdout.channel.recv_exit_status() if out: for line in out.split("\n")[:5]: print(f" {line}") return out, err, status def main(): print("=" * 50) print(" 重新部署 MBTI 问卷") print("=" * 50) c = connect() print("[连接] OK") try: # 1. 打包更新后的 seed_data.py print("\n--- 打包 ---") buf = io.BytesIO() with tarfile.open(fileobj=buf, mode="w:gz") as tar: tar.add(r"C:\Users\simon\WorkBuddy\2026-05-20-15-22-53\deploy\backend\seed_data.py", arcname="seed_data.py") b64_data = base64.b64encode(buf.getvalue()).decode("ascii") print(f" 打包完成: {len(b64_data)/1024:.1f} KB") # 2. 上传并覆盖 print("\n--- 上传 ---") decode_cmd = "base64 -d > /volume1/docker/gaokao-portal/backend/seed_data.py" transport = c.get_transport() channel = transport.open_session() channel.exec_command(decode_cmd) channel.sendall(b64_data.encode("ascii")) channel.shutdown_write() while not channel.exit_status_ready(): time.sleep(0.1) print(" 上传完成") # 3. 删除旧数据库(触发重新 seed) print("\n--- 重建数据库 ---") run(c, f"rm -f {NAS_DEPLOY_PATH}/backend/data/gaokao.db", "删除旧数据库") # 4. 重启容器(触发 seed 脚本执行) print("\n--- 重启容器 ---") run(c, f"cd '{NAS_DEPLOY_PATH}' && {SUDO_DOCKER} compose restart backend", "重启后端容器") # 等待容器完全启动 print(" 等待后端启动...") time.sleep(8) # 5. 验证 print("\n--- 验证问卷列表 ---") run(c, f"curl -s http://localhost:8080/api/questionnaires | python3 -c \"import sys,json; data=json.load(sys.stdin); print('问卷数量:', len(data)); [print(f\\\" {{i+1}}. {{q['title']}}\\\") for i,q in enumerate(data)]\"", "获取问卷列表") print("\n" + "=" * 50) print(" MBTI 问卷已添加!") print("=" * 50) finally: c.close() if __name__ == "__main__": main()