从 Paramiko SSH exec_command 连续获取输出 [英] Get output from a Paramiko SSH exec_command continuously
问题描述
我正在使用 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屋!