paramiko print exec_command result immediately

1.1k views Asked by At

I know exec_command returns 3 streams, but I'm unable to print the output as it should arrive to these streams.

client = SSHClient()
client.load_system_host_keys()
client.connect('ssh.example.com')
stdin, stdout, stderr = client.exec_command('ls -l; sleep 10; ls -l')
for line in stdout.readlines():
  print line
for line in stderr.readlines():
  print line

This seems to output new lines only at the end when the entire command has been finished. I'd like to receive the characters as they are generated by the remote commands. Is this possible?

1

There are 1 answers

0
Praneeth On

To read the output on your terminal, the method i knew is to stream the readbinaries and writebinaries straight from the ssh session into your terminal

import paramiko
import os
import sys

host_address = ''
USER = ''
PASSWORD = ''

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host_address, user=USER, password=PASSWORD)

#Time to invoke the shell from paramiko support
client_shell = client.INVOKE_SHELL()
standard_input = client_shell.makefile('wb')
standard_output = client_shell.makefile('rb')

standard_input.write('''
ls -l
sleep 10
ls -l
''')
print standard_output.read()

#Close all the streams and ssh connection in the end to flush the session

standard_input.close()
standard_output.close()
client.close()