Paramiko with continuous stdout
Solution 1:
Of course there is a way to do this. Paramiko execute_command
is async, buffers are filled while data arrives regardless of your main thread.
In your example stdout.read(size=None)
will try to read the full buffer size at once. Since new data is always arriving, it won't ever exit. To avoid this, you could just try to read from stdout
in smaller chunks. Here's an example that reads buffers bytewise and yields lines once a \n
is received.
stdin,stdout,stderr = ssh.exec_command("while true; do uptime; done")
def line_buffered(f):
line_buf = ""
while not f.channel.exit_status_ready():
line_buf += f.read(1)
if line_buf.endswith('\n'):
yield line_buf
line_buf = ''
for l in line_buffered(stdout):
print l
You can increase performance by tweaking the code to use select.select()
and by having bigger chunk sizes, see this answer that also takes into account common hang and remote command exit detection scenarios that may lead to empty responses.