-1

I am using Paramiko to control a VM over SSH. When I send any command it executes almost instantly but when reading the output from stdout it take forever.

I get around 5 seconds for a ls to read:

Time to execute command: 0.1445319652557373

Time to read output: 5.382704973220825

Here is a snippit:

import time
import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname="192.168.0.123",
        port=1234,
        username="admin",
        password="admin")

t1 = time.time()
stdin, stdout, stderr = ssh.exec_command("powershell -command \"ls -recurse .\"")
t2 = time.time()

t3 = time.time()
print(stdout.readlines())
t4 = time.time()

print(t2 - t1)
print(t4 - t3)

Thank you!

1
  • 1
    The exec_command does not execute the command completely. It only starts the execution. It's actually the readlines that waits for the command to complete. See Paramiko with continuous stdout. Or do you have any proof that Paramiko is actually reading the output slower than other SSH clients? How long does it take to execute ssh [email protected] powershell -command "ls -recurse ."? Commented Jun 17, 2021 at 13:35

1 Answer 1

1

stdout.readlines() Is reading all lines before your subprocess finishes and sends EOF to your main process. If you want to read line by line when available, then do for line in exp.stdout, the file object allows you to iterate over each line as its feed through the pipe. Otherwise it would probably be better to use stdout, stderr = Subprocess.communicate(None) as the communicate method uses a better system calls to read data from a Subprocess (like epoll, select, poll).

Sign up to request clarification or add additional context in comments.

3 Comments

How can you use Subprocess.communicate with SSH?
OK, but that's a completely different approach (and inferior to the one taken by OP).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.