Paramiko, exec_command get the output stream continuously

自闭症网瘾萝莉.ら 提交于 2019-12-10 17:15:04

问题


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.


回答1:


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.




回答2:


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()



回答3:


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



来源:https://stackoverflow.com/questions/31317198/paramiko-exec-command-get-the-output-stream-continuously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!