1

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.

Community
  • 1
  • 1

1 Answers1

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.

Dmitry Ermolov
  • 2,077
  • 1
  • 15
  • 24
  • I have some similar issue and your code helped but if try to send more than one command, the loop does not break. Looks like the `if not buf: break` portion is not working. I can't find anything on the internet on how to compare bytes in the buffer. Any thoughts? – Hellyeah Feb 12 '21 at 14:02