【问题标题】:subprocess: stdout and stderror seem interchanged or mixed子进程:stdout 和 stderr 似乎互换或混合
【发布时间】:2013-07-30 21:12:46
【问题描述】:

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

【问题讨论】:

  • 您的命令应该失败 -- "-p %d" % port 应该是两个参数:"-p", str(port)。如果 ssh 在 stdout 上生成足够的输出来填充其操作系统管道缓冲区,那么它就会死锁。使用 ssh.communicate() 而不是 readlines() 来避免它。

标签: subprocess


【解决方案1】:
return error,result

和

result1, error1 = sshcmd(...)

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

【讨论】:

  • 谢谢!傻我!注 3:仇恨无济于事 ;)
猜你喜欢
  • 2023-04-06
  • 1970-01-01
  • 2011-07-07
  • 2020-06-23
  • 1970-01-01
  • 2018-03-16
  • 1970-01-01
  • 1970-01-01
  • 2018-07-31
相关资源
最近更新 更多