使用子进程通过 ssh 连接到主机。
这是我用来以我的用户身份通过 ssh 和运行命令的代码片段。当我尝试使用 sudo 命令时,我收到与 tty 相关的错误——而不是终端(类似的东西)
sshProcess = subprocess.Popen(['ssh', hostname], stdin=subprocess.PIPE, stdout = subprocess.PIPE, universal_newlines=True, bufsize=0)
sshProcess.stdin.write("hostname\n")
sshProcess.stdin.write("ls -ldr %s \n"%path)
sshProcess.stdin.write("pwd \n")
sshProcess.stdin.close()
for line in sshProcess.stdout:
if line == "END\n":
break
print(line,end="")
但是我无法在命令下运行
sshProcess.stdin.write("sudo su - serviceuser \n")
最佳答案
您可以通过指定 -t 选项强制进行伪 tty 分配。
subprocess.Popen(['ssh -t', hostname], .....
来自 man ssh
-t
Force pseudo-tty allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services. Multiple -t optionsforce tty allocation, even if ssh has no local tty.
关于python - SSH 从我的本地机器到 linux 主机和 sudo 到 root 用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42882748/