36 lines
1.1 KiB
Python
36 lines
1.1 KiB
Python
#!/usr/bin/env python3
|
|
# 通过 SSH 在远端以 sudo 执行脚本(从 stdin 读取)
|
|
# 用法: python3 remote_run.py <host> <port> <user> < script.sh
|
|
# 依赖环境变量 SSHPASS
|
|
import os, sys, paramiko
|
|
|
|
|
|
def main():
|
|
host = sys.argv[1]
|
|
port = int(sys.argv[2]) if len(sys.argv) > 2 else 22
|
|
user = sys.argv[3] if len(sys.argv) > 3 else "root"
|
|
pw = os.environ.get("SSHPASS")
|
|
if not pw:
|
|
sys.stderr.write("ERROR: 请先设置环境变量 SSHPASS\n")
|
|
sys.exit(1)
|
|
script = sys.stdin.read()
|
|
c = paramiko.SSHClient()
|
|
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
|
c.connect(host, port, user, password=pw, timeout=30)
|
|
stdin, stdout, stderr = c.exec_command("sudo -S bash -s", timeout=1800)
|
|
stdin.write(pw + "\n")
|
|
stdin.write(script)
|
|
stdin.flush()
|
|
stdin.channel.shutdown_write()
|
|
sys.stdout.write(stdout.read().decode(errors="replace"))
|
|
err = stderr.read().decode(errors="replace")
|
|
if err.strip():
|
|
sys.stderr.write("STDERR:\n" + err)
|
|
code = stdout.channel.recv_exit_status()
|
|
c.close()
|
|
sys.exit(code)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|