0

我正在尝试自动化交互式 ssh 调用(见注 1),如下所示:

SSHBINARY = '/usr/bin/ssh'
ASKPASS   = '/home/mz0/checkHost/askpass.py'

def sshcmd(host,port,user,password,cmd):
    env0 = {'SSH_ASKPASS': ASKPASS, 'DISPLAY':':9999'}
    ssh = subprocess.Popen([SSHBINARY,"-T","-p %d" % port,
        "-oStrictHostKeyChecking=no", "-oUserKnownHostsFile=/dev/null", 
        "%s@%s" % (user,host), cmd],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    env=env0,
    preexec_fn=os.setsid
    )
    error = ssh.stderr.readlines()
    result = ssh.stdout.readlines()
    return error,result

host = 'localhost'
port = 22
user = 'try1'
password = '1try' # unused, hardcoded in ASKPASS
cmd = 'ls'

result1, error1 = sshcmd(host,port,user,password,cmd)
if result1 : print "OUT: %s" % result1
if error1  : print "ERR: %s" % error1

自从我得到这个后,我正在做一些愚蠢的事情:

OUT: ["Warning: Permanently added 'localhost' (RSA) to the list of known hosts.\r\n"]
ERR: ['['Desktop\n', ..., 'Videos\n']']

显然 stdout 和 stderr 被交换了(注 2)。你能指出我的错误吗?

注意 1:我很清楚无密码 ssh、忽略主机密钥等的危险,以及对自动化交互式 ssh 的厌恶请求。

注意 2:在 shell 中运行相同的命令确认 stdout 和 stderr 在我的代码中被交换

ssh -o 'UserKnownHostsFile /dev/null' -o 'StrictHostKeyChecking no' \
try1@localhost ls > ssh-out 2> ssh-error
4

1 回答 1

2
return error,result

result1, error1 = sshcmd(...)

只需交换周围的任何一个。

于 2013-07-30T16:07:23.583 回答