具有连续标准输出的 Paramiko [英] Paramiko with continuous stdout

查看:90
本文介绍了具有连续标准输出的 Paramiko的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Paramiko 向远程 Linux 服务器运行一些 ssh 命令.这些命令将在控制台中连续输出,我想在本地控制台窗口中打印这些所有信息.

I use Paramiko to run some ssh commands to the remote Linux server. The commands will have continuous output in the console and I want to print these all information in the local console window.

stdin, stdout, stderr = ssh.client.exec_command("ls")
for line in stdout.read()
    print line,
ssh.client.close()

因此,如果我像这样编写代码,则所有输出信息都将发送回给我,直到命令完成执行,而我想实时打印输出.

So if I write the code like this, all the output information will be sent back to me until the command finishes executing while I want to print the output in live.

非常感谢.

推荐答案

当然有办法做到这一点.Paramiko execute_command 是异步的,无论您的主线程如何,缓冲区都会在数据到达时填充.

Of course there is a way to do this. Paramiko execute_command is async, bufferes are filled while data arrives regardless of your main thread.

在您的示例中,stdout.read(size=None) 将尝试一次读取完整的缓冲区大小.由于新数据总是到达,它永远不会退出.为了避免这种情况,您可以尝试以较小的块从 stdout 中读取.这是一个按字节读取缓冲区并在收到 \n 后生成行的示例.

In your example stdout.read(size=None) will try to read the full buffer size at once. Since new data is always arriving, it won't ever exit. To avoid this, you could just try to read from stdout in smaller chunks. Here's an example that reads buffers bytewise and yields lines once a \n is received.

sin,sout,serr = ssh.exec_command("while true; do uptime; done")

def line_buffered(f):
    line_buf = ""
    while not f.channel.exit_status_ready():
        line_buf += f.read(1)
        if line_buf.endswith('\n'):
            yield line_buf
            line_buf = ''

for l in line_buffered(sout):
    print l

您可以通过调整代码以使用 select.select() 和更大的块大小来提高性能,请参阅 这个答案 还考虑了可能导致空响应的常见挂起和远程命令退出检测场景.

You can increase performance by tweaking the code to use select.select() and by having bigger chunk sizes, see this answer that also takes into account common hang and remote command exit detection scenarios that may lead to empty responses.

这篇关于具有连续标准输出的 Paramiko的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆