从 Paramiko SSH exec_command 连续获取输出 [英] Get output from a Paramiko SSH exec_command continuously

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

问题描述

我正在使用 paramiko 通过 ssh 在远程机器上执行长时间运行的 python 脚本.效果很好,目前没有问题.

I am executing a long-running python script via ssh on a remote machine using paramiko. Works like a charm, no problems so far.

不幸的是,stdout(分别为stderr)仅在脚本完成后显示!但是,由于执行时间的原因,我更喜欢在打印每一行时输出它,而不是之后输出.

Unfortunately, the stdout (respectively the stderr) are only displayed after the script has finished! However, due to the execution time, I'd much prefer to output each new line as it is printed, not afterwards.

remote = paramiko.SSHClient()
remote.set_missing_host_key_policy(paramiko.AutoAddPolicy())
remote.connect("host", username="uname", password="pwd")
 
# myScript produces continuous output, that I want to capture as it appears    
stdin, stdout, stderr = remote.exec_command("python myScript.py")
stdin.close()
for line in stdout.read().splitlines():
    print(line)

如何实现? 注意:当然可以将输出通过管道传输到一个文件,然后通过另一个 ssh 会话减少"这个文件,但这非常难看,我需要一个更干净的、理想的 Pythonic 解决方案 :)

推荐答案

read([size]) 文档,如果你不指定size,它会一直读取到 EOF,这使得脚本一直等到命令在从 read() 返回并打印任何输出之前结束.

As specified in the read([size]) documentation, if you don't specify a size, it reads until EOF, that makes the script wait until the command ends before returning from read() and printing any output.

检查这个答案:如何在 Python 中循环直到 EOF?如何做一个While not EOF",了解如何耗尽类文件对象的例子.

Check this answers: How to loop until EOF in Python? and How to do a "While not EOF" for examples on how to exhaust the File-like object.

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

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