2

I am having some trouble with Paramiko module while running a command on remote server.

def check_linux(cmd, client_ip, client_name):
    port = 22
    username = 'xxxxxxx'
    password = 'xxxxxxxx'
    try:
        sse = paramiko.SSHClient()
        sse.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        sse.connect(client_ip, port, username, password, timeout=5)
        (stdin, stdout, stderr) = sse.exec_command("my cmd")
        del stdin
        status = stdout.read()
        status = status.decode('ascii')
        return status
    except (paramiko.SSHException, socket.error, socket.timeout, Exception) as error:
        print "Unable to Authenticate/logon:" ,client_name,client_ip,
        sys.exit()
[root@xxxxxxx star_script]# python
Python 2.7.5 (default, Oct 11 2015, 17:47:16)
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import paramiko
>>> port = 22
>>> username = 'xxxxxxxx'
>>> password = 'xxxxxxxxxx'
>>> client_ip = 'xxxxxxx'
>>> cmd = 'openssl s_client -connect xxxxxxx:xxxxx'
>>> sse = paramiko.SSHClient()
>>> sse.set_missing_host_key_policy(paramiko.AutoAddPolicy())
>>> sse.connect(client_ip, port, username, password, timeout=5)
>>> (stdin, stdout, stderr) = sse.exec_command(cmd)
>>> status = stderr.read()

For some server's, command execution doesn't happen and the program is not executing further. I've tried readlines() and stdout.channel.eof_received, but both seems to be not working.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
sunny
  • 35
  • 4

1 Answers1

2

The .read will wait until the command finishes, what it never does.

Instead, wait for the command to finish first. If it is taking too long, kill the command (using stdout.channel.close()).

You can use the code from Python Paramiko exec_command timeout doesn't work?:

timeout = 30
import time
endtime = time.time() + timeout
while not stdout.channel.eof_received:
    time.sleep(1)
    if time.time() > endtime:
        stdout.channel.close()
        break
status = stdout.read()

Though you can use the above code, only if the command produces very little output. Otherwise the code might deadlock. For a robust solution, you need to read the output continuously.
See A command does not finish when executed using Python Paramiko exec_command

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992