subprocess:stdout和stderr似乎互换或混合

时间:2013-07-30 15:57:42

标签: subprocess

我正在尝试自动化交互式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

1 个答案:

答案 0 :(得分:2)

return error,result

result1, error1 = sshcmd(...)

只需交换其中任何一个。