Search code examples
pythonsshstdoutparamikoreadline

Executing commands of interactive tool and reading their output with Paramiko


I am preparing a code to access a remote server using ssh with Paramiko and to run some commands and see the output of stdout.

I have tested the code with a Ubuntu server and it worked perfectly, but when I tested the code with a different server (which is a Windows server and the interface to a telecommunication machine) the stdout is not read, The ("Successfully executed command on remote server") is printed but the following ("lines are read") is not printed So I concluded that the code is hanging at stdout=stdout.readlines() The code is copied below, can you please help me figuring out what could be the reason behind this failure?

I want also to add that if I use PuTTY to execute the commands on that server I get the correct output.

import paramiko
import os
user_name = "****"
passwd = "******"
ip = "*.*.*.*"

print ("Please wait creating ssh client ...")
ssh_client = paramiko.SSHClient()     #Create sshclient instance
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print ("Please wait, connecting to remote server")
ssh_client.connect(hostname=ip,username=user_name,password=passwd)
cmd="mml \n command2"
print ("Please wait, executing command on remote server")
stdin,stdout,stderr=ssh_client.exec_command(cmd)
print ("Successfully executed command on remote server")
stdout=stdout.readlines()
print ("lines are read")
stdout="".join(stdout)
ssh_client.close()
print ("Connection closed")
print (stdout)
os.system("pause")

Solution

  • The command that you are executing is interactive. When started, it waits for subcommands. While you execute it and wait for the command to finish (by calling readlines). What never happens.

    You have to feed the subcommands to your command to have it do something.
    See Pass input/variables to command/script over SSH using Python Paramiko.

    You will also have to make the command quit (by sending a subcommand like exit/quit/bye).