python - paramiko立即打印exec_command结果

标签 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

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

最佳答案

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

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()

关于python - paramiko立即打印exec_command结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31041530/

相关文章:

python - 在 Python 中乘以非常大的二维数组

python - TensorFlow中标准化函数的作用是什么?

mysql 访问被拒绝,ssh 数据库主机

bash - SSH之后如何使用bash脚本使用私钥创建到远程计算机的隧道

Node.js 流可读转换

python - 以特定方式组合一组数组

python - 训练和测试后,我如何处理新数据?

git - 为什么 GitHub 推荐 HTTPS 而不是 SSH?

java - 如何从rtf文档文件的文件列表中获取InputStream?

stream - 概念 : Channel vs. 流