import os, sys, paramiko PW = os.environ.get("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, allow_fail=False): print(f"$ {cmd}") si, so, se = c.exec_command(cmd, timeout=20) out = so.read().decode("utf-8", "replace") err = se.read().decode("utf-8", "replace") rc = so.channel.recv_exit_status() if out: print(out, end="") if err: print("[err]", err, end="", file=sys.stderr) print(f" -> rc={rc}") if rc != 0 and not allow_fail: raise SystemExit(f"failed: {cmd}") return out, err, rc # 1) 备份 run("cp -a /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%s)") # 2) 改 PubkeyAuthentication run("sed -i -E 's/^#?\\s*PubkeyAuthentication.*/PubkeyAuthentication yes/' /etc/ssh/sshd_config") # 3) 确认 run("grep -n '^[^#]*PubkeyAuthentication' /etc/ssh/sshd_config") # 4) 语法检查 run("sshd -t && echo 'sshd config OK'") # 5) 重启(用 service 或 systemctl,Ubuntu 24 用 systemd) # 先试 systemctl,失败回退 service out, _, _ = run("systemctl is-active ssh 2>/dev/null || systemctl is-active sshd 2>/dev/null || echo NONE", allow_fail=True) if "active" in out: run("systemctl restart ssh || systemctl restart sshd") else: run("service ssh restart || service sshd restart") # 6) 再确认 sshd 配置生效 run("sshd -T 2>/dev/null | grep -i pubkeyauth") c.close() print("DONE")