import os, paramiko PW = os.environ["REMOTE_PASS"] c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) c.connect("207.57.129.228", port=19717, username="root", password=PW, timeout=15, allow_agent=False, look_for_keys=False) def run(cmd, t=30): si, so, se = c.exec_command(cmd, timeout=t) out = so.read().decode("utf-8", "replace") err = se.read().decode("utf-8", "replace") rc = so.channel.recv_exit_status() print(f"$ {cmd}") if out: print(out, end="") if err: print("[err]", err, end="", file=__import__("sys").stderr) print(f" rc={rc}") # 1) 服务器 git pull run("cd /srv/news && sudo -u news git pull --rebase 2>&1 | tail -10") # 2) 重跑部署脚本(直接重跑,前面的 docker 镜像已构建缓存) run("pkill -f deploy_news.sh 2>/dev/null; sleep 2; rm -f /root/deploy_news.log; echo ===restart===") si, so, se = c.exec_command("nohup env SSHD_PORT=19717 bash /root/deploy_news.sh > /root/deploy_news.log 2>&1 & echo $!", timeout=10) print(f"deploy started, PID={so.read().decode().strip()}") c.close()