Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing real-time SSH output using Python 3.x

I have a script that SSH connects from Windows7 to a remote ubuntu server and executes a command. The script returns Ubuntu command output to the Windows cmd window in one go after the command has executed and finished. I am just wondering if there is anyway to return real-time SSH output in my script below, or do I always have to wait for the command to finish before seeing the output.

Here's my working code:

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
host = '9.10.11.12'
port, user, password = 22, 'usr', 'pass'
ssh.connect(host, port,  user, password)
stdin,stdout,stderr = ssh.exec_command("cd /opt/app && ./app-tool some_command")

for line in stdout.readlines():
    print(line)

ssh.close()

Alternatively, if this is not possible with SSH how would I introduce a spinning cursor icon into the above script? Thanks.

like image 924
MikG Avatar asked Dec 02 '25 09:12

MikG


1 Answers

Figured it out in the end, I used 'iter' method in the following line:

for line in iter(stdout.readline,""): 
    print(line)
like image 154
MikG Avatar answered Dec 06 '25 15:12

MikG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!