【发布时间】:2023-11-29 17:06:01
【问题描述】:
我正在尝试检查远程计算机上是否存在可执行文件,然后运行该可执行文件。为此,我使用子进程运行ssh <host> ls <file>,如果成功,则运行ssh <host> <file>。当然,ssh 要求输入密码,我想自动提供密码。另外,我想从 ls 中获取返回码,并通过运行命令获取 stdout 和 stderr。
所以我知道需要communicate() 方法,以避免死锁,但我无法获得Popen(stdin) 识别的密码。我也在使用 Python 2.4.3,并坚持使用该版本。这是我目前得到的代码:
import os
import subprocess as sb
def WallHost(args):
#passwd = getpass.getpass()
passwd = "password"
for host in args:
# ssh to the machine and verify that the script is in /usr/bin
sshLsResult = sb.Popen(["ssh", host, "ls", "/usr/bin/wall"], stdin=sb.PIPE, stderr=sb.PIPE, stdout=sb.PIPE)
(sshLsStdout, sshLsStderr) = sshLsResult.communicate(input=passwd)
sshResult = sshLsResult.returncode
if sshResult != 0:
raise "wall is not installed on %s. Please check." % host
else:
sshWallResult = sb.Popen(["ssh", host, "/usr/bin/wall", "hello world"], stdin=sb.PIPE, stderr=sb.PIPE, stdout=sb.PIPE)
(sshWallStdout, sshWallStderr) = sshWallResult.communicate(input=passwd)
print "sshStdout for wall is \n%s\nsshStderr is \n\n" % (sshWallStdout, sshWallStderr)
args = ["127.0.0.1", "192.168.0.1", "10.10.265.1"]
WallHost(args)
感谢您在接受该密码的过程中提供任何帮助。或者,如果您有更好的方法来检查可执行文件,然后在远程主机上运行它。 ;)
谢谢 安东尼
【问题讨论】:
-
哦,看起来很酷。我希望我可以使用它。但无法安装第 3 方包:仅限基本 Python 2.4.3。
标签: python subprocess stdout stdin