Skip to main content
 首页 » 编程设计

Python 子进程(不正确)合并 ssh 的 stderr 和 stdout

2024年10月01日6傻小

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

请您参考如下方法:

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

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