2

I'm using Paramiko to connect to a server via SSH, run a command to generate a report, then download the report to my local computer. Everything seems to work fine without an error, but the resulting file is blank on my local computer. I'm using Python 2.7 and the latest version of Paramiko. The file that I'm trying to download is a .csv . I've verified that the file contains data server-side.

The code I am using is below:

try:
    ssh = paramiko.SSHClient()

    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    ssh.connect(hostname, username=user_name, key_filename=key_file)
except:
    print 'error connecting'

try:
    stdin, stdout, stderr  = ssh.exec_command(report_cmd)
except:
    print 'error generating report'

try:

    sftp = ssh.open_sftp()  
    sftp.get(source_str, dest_str)

except:
    print 'failed to DL file' + str(sys.exc_info())

ssh.close()

1 Answers1

1

You are trying to download the file before the ssh.exec_command has finished.

You need to wait; the best way would be to read from stdout and/or stderr until EOF.

I think those reads will be blocking, but since you have nothing else to do until they finish anyway that should be fine. And I beleive EOF will look like an empty string: "".

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
  • Reading out the command's `stdout` and/or `stderr` until EOF would be a definitely better option. – glglgl Aug 18 '14 at 21:14
  • Thanks Ethan and glglgl! I knew the answer had to be something simple. It's working just fine now. Here is what I ended up adding below the ssh.exec_command line: "exit_status = stdout.channel.recv_exit_status()" , as found @ http://stackoverflow.com/a/6570087/3954183 – Paul Greene Aug 18 '14 at 21:46