连续从paramiko ssh exec_command获取输出 [英] get output from a paramiko ssh exec_command continuously

查看:756
本文介绍了连续从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解决方案:)

推荐答案

阅读( [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?,以获取有关如何耗尽类似File的对象的示例.

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天全站免登陆