gpt4 book ai didi

python - 如何为子进程提供密码并同时获取标准输出

转载 作者:行者123 更新时间:2023-11-30 23:35:43 25 4
gpt4 key购买 nike

我正在尝试检查远程计算机上是否存在可执行文件,然后运行所述可执行文件。为此,我使用子进程来运行 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)
<小时/>

如果您能帮助我们接受该密码,我们将不胜感激。或者,如果您有更好的方法来检查可执行文件,然后在远程主机上运行它。 ;)

谢谢安东尼

最佳答案

使用 authorized_keys 怎么样? 。这样就不需要输入密码了。

你也可以采取困难的方式(仅在 Linux 中工作):

import os
import pty

def wall(host, pw):
pid, fd = pty.fork()
if pid == 0: # Child
os.execvp('ssh', ['ssh', host, 'ls', '/usr/bin/wall'])
os._exit(1) # fail to execv

# read '..... password:', write password
os.read(fd, 1024)
os.write(fd, pw + '\n')

result = []
while True:
try:
data = os.read(fd, 1024)
except OSError:
break
if not data:
break
result.append(data)
pid, status = os.waitpid(pid, 0)
return status, ''.join(result)

status, output = wall('localhost', "secret")
print status
print output

http://docs.python.org/2/library/pty.html

关于python - 如何为子进程提供密码并同时获取标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17118239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com