Python 从 paramiko ssh exec_command 连续获取输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31834743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get output from a paramiko ssh exec_command continuously
提问by Lukas N.P. Egger
I am executing a long-running python script via ssh on a remote machine using paramiko. Works like a charm, no problems so far.
我正在使用 paramiko 通过 ssh 在远程机器上执行长时间运行的 python 脚本。像魅力一样工作,到目前为止没有问题。
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)
How can this be achieved?Note: Of course one could pipe the output to a file and 'less' this file via another ssh session, but this is very ugly and I need a cleaner, ideally pythonic solution :)
如何做到这一点?注意:当然,可以通过另一个 ssh 会话将输出通过管道传输到一个文件并“减少”这个文件,但这非常难看,我需要一个更干净的、理想的 pythonic 解决方案:)
采纳答案by KurzedMetal
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.
正如read( [size]) 文档中所指定的,如果您不指定 a size
,它将一直读取到 EOF,这使得脚本在返回read()
并打印任何输出之前等待命令结束。
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.
检查这个答案:How to loop until EOF in Python? 以及如何执行“While not EOF”以获取有关如何耗尽类 File 对象的示例。
回答by James Shrum
I was facing a similar issue. I was able to solve it by adding get_pty=True to paramiko:
我面临着类似的问题。我能够通过向 paramiko 添加 get_pty=True 来解决它:
stdin, stdout, stderr = client.exec_command("/var/mylongscript.py", get_pty=True)
回答by Jorge Leitao
A minimal and complete working example of how to use this answer(tested in Python 3.6.1)
如何使用此答案的最小且完整的工作示例(在 Python 3.6.1 中测试)
# run.py
from paramiko import SSHClient
ssh = SSHClient()
ssh.load_system_host_keys()
ssh.connect('...')
print('started...')
stdin, stdout, stderr = ssh.exec_command('python -m example', get_pty=True)
for line in iter(stdout.readline, ""):
print(line, end="")
print('finished.')
and
和
# example.py, at the server
import time
for x in range(10):
print(x)
time.sleep(2)
run on the local machine with
在本地机器上运行
python -m run