【问题标题】:Python subprocess (incorrectly?) merging stderr and stdout for sshPython子进程(不正确?)为ssh合并stderr和stdout
【发布时间】:2018-03-16 19:01:10
【问题描述】:

我正在尝试通过 python 的子进程和 ssh 运行各种 linux 命令。我希望能够运行该命令并检查 stderrstdout 长度以确定该命令是否成功。例如,如果没有错误,则表示成功。问题是在初始连接后,所有输出都将转到stdout

我确实尝试过使用 paramiko,但不断得到不可靠的身份验证行为。如果我能让它发挥作用,这种方法似乎更可靠。

import subprocess
import os
import pty
from select import select

class open_ssh_helper(object):
    def __init__(self, host="127.0.0.1", user="root"):
        self.host = host
        self.user = user
        self.cmd = ['ssh',
                    user +'@'+host, 
                    "-o", "StrictHostKeyChecking=no", 
                    "-o", "UserKnownHostsFile=/dev/null"]

        self.prompt = '~#'
        self.error = ''
        self.output = ''

        self.mtty_stdin, self.stty_stdin = pty.openpty()
        self.mtty_stdout, self.stty_stdout = pty.openpty()
        self.mtty_stderr, self.stty_stderr = pty.openpty()

        self.ssh = subprocess.Popen(self.cmd,
                                    shell=False,
                                    stdin=self.stty_stdin,
                                    stdout=self.stty_stdout,
                                    stderr=self.stty_stderr)
        self._read_stderr()
        self._read_stdout()

    def _reader(self, read_pty):
        char = ""
        buf = ""
        while True:
            rs, ws, es = select([read_pty], [], [], 0.5)
            if read_pty in rs:
                char = os.read(rs[0], 1)
                buf += char 
            else:
                break

        return buf

    def _read_stderr(self):
        self.error = self._reader(self.mtty_stderr)

    def _read_stdout(self):
        self.output = self._reader(self.mtty_stdout)

    def execute(self, command):
        os.write(self.mtty_stdin, command)

        self._read_stderr()
        self._read_stdout()

if __name__=='__main__':
    ss = open_ssh_helper('10.201.202.236', 'root')

    print "Error: \t\t: " + ss.error
    print "Output: \t: " + ss.output

    ss.execute("cat /not/a/file\n")

    print "Error: \t\t: " + ss.error
    print "Output: \t: " + ss.output

输出类似:

Error:      : Warning: Permanently added '10.201.202.236' (ECDSA) to the list of known hosts.
Debian GNU/Linux 8
BeagleBoard.org Debian Image xxxx-xx-xx
Support/FAQ: http://elinux.org/Beagleboard:BeagleBoneBlack_Debian

Output:     : Last login: Thu Oct  5 07:32:06 2017 from 10.201.203.29
root@beaglebone:~# 
Error:      : 
Output:     : cat /not/a/file
cat: /not/a/file: No such file or directory
root@beaglebone:~# 

我希望 cat: /not/a/file: No such file or directory 行会被打印为上面的错误行。但是,由于某种原因,stdout 似乎同时打印了输出和错误。

【问题讨论】:

    标签: python linux ssh subprocess


    【解决方案1】:

    ssh 将远程系统上的 stdout 和 stderr 作为单个流拉回,因此它们都通过 ssh 标准输出。

    如果您想分离远程系统上的两个流,您必须将其中一个或两个流重定向到远程文件,然后读取文件。或者不太可靠但可能更容易,您可以通过一个过滤器重定向 stderr,该过滤器在每行的开头放置类似 'STDERR:' 的内容,然后以这种方式再次拆分流。

    【讨论】:

    • 谢谢@Duncan。你的答案是正确的我已经进一步研究了为什么 paramiko 返回 stderr 而最初发布的代码没有。我了解到使用结构 ssh hostname command 将返回,就好像命令在本地运行一样。在这种情况下,返回码和stderrstdout 都可以访问。在原始代码中,我尝试打开一个 ssh shell,然后通过 shell 将命令传递给远程系统。正如邓肯指出的那样,这是行不通的。最终的解决方案是学会正确使用 subprocess.call()
    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    • 2013-11-08
    相关资源
    最近更新 更多