Paramiko finish process before reading all output

自作多情 提交于 2020-01-06 23:54:50

问题


I'm Trying to make a real time SSH Library, but as usually getting stuck on things, I have taken this code from Long-running ssh commands in python paramiko module (and how to end them). But this code doesn't prints the whole output.

I guess that when the while loop exits on channel.exit_status_ready() the channel still have data to read. I've been trying to fix this but the fix was not on all inputs.

How can I make this work to print all kind of commands?

import paramiko
import select

client = paramiko.SSHClient()
client.load_system_host_keys()
client.connect('host.example.com')
channel = client.get_transport().open_session()
channel.exec_command("cd / && ./test.sh")
while True:
    if channel.exit_status_ready():
        break
    rl, wl, xl = select.select([channel], [], [], 0.0)
    if len(rl) > 0:
        print channel.recv(1024)

test.sh:

echo 1
wait 1
echo 2
wait 1
echo 3

Output:

1

2

Process finished with exit code 0

Thanks.


回答1:


I couldn't reproduce problem with your command, but I can reproduce it with command like cat some_big_file.txt.

So looks like you are right in your hypothesis. Exit status can be ready before you read all the stuff from your channel. It's not clear if you really need to use select. If not I would rewrite loop:

while True:
    buf = channel.recv(1024)
    if not buf:
        break
    print buf

Such loop will keep reading the channel while it has some data in it. If you really want to use select you can put the above loop just after your loop. It will read and print remaining data.



来源:https://stackoverflow.com/questions/37032210/paramiko-finish-process-before-reading-all-output

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