-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!

mihdim777
  • 3
  • 2
  • 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](https://stackoverflow.com/q/25260088/850848). 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 admin@192.168.0.123 powershell -command "ls -recurse ."`? – Martin Prikryl Jun 17 '21 at 13:35

1 Answers1

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

David Meu
  • 1,527
  • 9
  • 14