nadobando
nadobando

Reputation: 123

Paramiko finish process before reading all output

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.

Upvotes: 1

Views: 3378

Answers (1)

Dmitry Ermolov
Dmitry Ermolov

Reputation: 2237

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.

Upvotes: 1

Related Questions