get output from a paramiko ssh exec_command continuously

我的未来我决定 提交于 2019-11-27 07:40:01
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.

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.

I was facing a similar issue. I was able to solve it by adding get_pty=True to paramiko:

stdin, stdout, stderr = client.exec_command("/var/mylongscript.py", get_pty=True)

A minimal and complete working example of how to use this answer (tested in 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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!