【发布时间】:2015-11-14 12:19:29
【问题描述】:
我正在使用 paramiko 收集有关远程主机的一些信息并在从 stderr 频道读取 (read()/readline()/readlines()) 时遇到问题。
有时stderr.read() 会返回一个空字符串,在我看来它是竞争条件的结果。
但是,根据我在互联网上找到的文档和示例,这似乎是正确的方法。
我还尝试打开一个专用通道并使用 chan.recv_ready() / chan.recv_stderr_ready() 并通过 chan.recv() / chan.recv_stderr() 从各个通道循环读取,但这会导致相同的行为。
这是一个最小的测试用例 - 在我的设置中 - 可靠地导致了这种行为。
import paramiko
class SSH:
def __init__(self):
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect('127.0.0.1', port=31337, username='root', password='root')
self.stdout = ''
self.stderr = ''
self.exit_code = 0
def _run_cmd(self, cmd):
self.stdout = ''
self.stderr = ''
stdin, stdout, stderr = self.ssh.exec_command(cmd)
self.stdout = stdout.read()
self.stderr = stderr.read()
while not stdout.channel.exit_status_ready():
pass
self.exit_code = stdout.channel.recv_exit_status()
if self.exit_code:
print("ERROR: " + self.stderr)
def process_list(self):
self._run_cmd('ls /proc/ | grep -E "^[0-9]+$" | grep -v $$')
lines = self.stdout.split('\n')[:-1]
data = []
for process in lines:
process_data = {}
process_data['pid'] = int(process)
# fetching and parsing process status information from /proc/[PID]/status
self._run_cmd('cat /proc/%d/status' % (int(process)))
data.append(self.stdout)
return data
data = SSH()
while True:
print data.process_list()
经过几次运行(如果不是第一次),我得到的是:
ERROR:
虽然我期待:
ERROR: cat: /proc/12883/status: No such file or directory
如何确保 stderr 已准备好从/我读取 stderr 上的所有数据?
【问题讨论】:
标签: python ssh paramiko stderr