python - SSH 从我的本地机器到 linux 主机和 sudo 到 root 用户

标签 python linux ssh sudo tty

使用子进程通过 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/

相关文章:

linux - echo "$myvar"| awk 'FNR ....' 不回应任何东西

python - 如何检测/捕获来自convertapi的错误代码,以便我的python应用程序不会失败?

python - 将图像拼接在一起 Opencv -Python

c++ - 如何使用 NetBeans 调试不是用 NetBeans 编译的 C++ 库?

linux - 如何在 screen session 中配置默认​​ TERM?

shell - 检查谁通过SSH删除文件

python - 如何从 Object dtype 中提取特定的单词/数值?

python - 名称错误 : name 'User' is not defined (when flask shell)

linux - CentOS 6 中删除文件夹/var/lib/* 时如何修复

C# SSH 隧道 Postgres 数据库连接