6

I dry on a Python script. I create a python script for a given IP will connect via Paramiko to a server to execute another Python script.

Here is some code:

self._client = paramiko.SSHClient()
self._client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self._client.connect(self._ip, username=self._server['username'], password=self._server['password'])
channel = self._client.get_transport().open_session()
channel.exec_command('python3 /tmp/scrap.py /tmp/' + self._ip + '.txt 0 1')

The script "scrap.py" returns every X seconds a line in the console of the remote machine, but I can not recover as and when these lines in the script above (at the exit of exec_command (. ..)).

Is this possible, and if so have you any idea how?

Thank you in advance.

3 Answers3

3

This should do the trick:

stdin, stdout, stderr = channel.exec_command("python myScript.py")
stdin.close()
for line in iter(lambda: stdout.readline(2048), ""):
    print(line, end="")

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.

Lukas N.P. Egger
  • 923
  • 2
  • 9
  • 12
1

I'm not sure if my version of paramiko is outdated, but Lukas N.P. Egger solution didn't work for me, as channel.exec_command did not return three things, only one. This worked for me:

print 'connecting'
transport = paramiko.Transport((IP_ADDRESS, 22))
transport.connect(username='USERNAME', password='PASSWORD')
print 'opening ssh channel'
channel = transport.open_session()
channel.set_combine_stderr(1)
channel.exec_command('cd render && python render.py')
while True:
  if channel.exit_status_ready():
    if channel.recv_ready():
      print 'done generating graph'
      break
  sys.stdout.write(channel.recv(1))
print 'closing ssh channel'
channel.close()
Daniel F
  • 13,684
  • 11
  • 87
  • 116
  • 1
    Looks like the other solution just had bad variable names. It's the `client.exec_command` that [returns 3-tuple](https://github.com/paramiko/paramiko/blob/v1.18.1/paramiko/client.py#L445). The lower-level channel `exec_command` does not return any value. – wim Feb 08 '19 at 22:27
0

What worked for me:
Use: sys.stdout.flush() in your readline-print loop

Tapomay
  • 191
  • 1
  • 2
  • 9