0

I am using the the python paramiko library to SSH into a FTP server. I am able to use the command line to access the server and retrieve a list of files using the sftp command, however paramiko seems to be doing something that prevents me from retrieving output. Here is my python code:

import paramiko
client = paramiko.SSHClient()

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

client.connect('###########',
        port=##,
        username='####',
        password='####',
        key_filename='#####')

stdin, stdout, stderr = client.exec_command('ls')

this all works just fine. However the next line

stdout.readline()

just sits there and hangs. Notice that per this thread I am not even trying to retrieve the full output, just the first line.

I also tried

stdin.close()
print(stdout.readlines())

which returns an empty string. This suggests that maybe the server is waiting for input, but when I use the command line I am able to just send the ls command and get the output so what command could it be waiting for?

Versions:

  • python 3.7.4
  • paramiko 2.7.1
Maile Cupo
  • 636
  • 1
  • 10
  • 26

1 Answers1

0

Your readline might be executing before there is a return from the remote host try:

import paramiko
client = paramiko.SSHClient()

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

client.connect('###########',
        port=##,
        username='####',
        password='####',
        key_filename='#####')

stdin, stdout, stderr = client.exec_command('ls')        
stdout.channel.recv_exit_status()
print(stdout.readline())

The recv_exit_status() will wait until there is a return from exec_command() on your remote host.

  • I have tried waiting up to 30s before executing the readline command. There are only a handful of files on the server (which is on aws) and I have a decent internet connection. I can't see that being the issue. – Maile Cupo Jun 02 '20 at 15:02
  • It sounds like you might be hanging on the client.connect() and not actually setting up the tunnel for exec_command(). Add a try catch around the connect and add an auth timeout arg `try: client.connect('###########', port=##, username='####', password='####', key_filename='#####', timeout=5.0) except (Exception) as e: return print('Error connecting to ssftp: {}'.format(e)) sys.exit(0)` – SpicestMemeLord Jun 02 '20 at 16:24