如何给子进程一个密码并同时获取标准输出


问题内容

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

感谢您提供任何帮助您接受密码的过程。或者,如果您有更好的方法来检查可执行文件,然后在远程主机上运行它。;)

thx安东尼


问题答案:

如何使用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