paramiko立即打印exec_command结果

时间:2015-06-25 04:58:44

标签: python ssh stream paramiko

我知道exec_command会返回3个流,但我无法打印输出,因为它应该到达这些流。

client = SSHClient()
client.load_system_host_keys()
client.connect('ssh.example.com')
stdin, stdout, stderr = client.exec_command('ls -l; sleep 10; ls -l')
for line in stdout.readlines():
  print line
for line in stderr.readlines():
  print line

这似乎仅在整个命令完成时才输出新行。我想收到远程命令生成的字符。这可能吗?

1 个答案:

答案 0 :(得分:0)

要读取终端上的输出,我知道的方法是将readbinaries和writebinaries直接从ssh会话流式传输到终端

import paramiko
import os
import sys

host_address = ''
USER = ''
PASSWORD = ''

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host_address, user=USER, password=PASSWORD)

#Time to invoke the shell from paramiko support
client_shell = client.INVOKE_SHELL()
standard_input = client_shell.makefile('wb')
standard_output = client_shell.makefile('rb')

standard_input.write('''
ls -l
sleep 10
ls -l
''')
print standard_output.read()

#Close all the streams and ssh connection in the end to flush the session

standard_input.close()
standard_output.close()
client.close()