Skip to main content
 首页 » 编程设计

python之Paramiko之sftp.get 下载空白文件

2025年05月04日13jillzhang

我正在使用 Paramiko 通过 SSH 连接到服务器,运行命令生成报告,然后将报告下载到我的本地计算机。一切似乎都没有错误地工作正常,但生成的文件在我的本地计算机上是空白的。我正在使用 Python 2.7 和最新版本的 Paramiko。我要下载的文件是 .csv 。我已经验证该文件包含数据服务器端。

我使用的代码如下:

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() 

请您参考如下方法:

您正在尝试在 ssh.exec_command 完成之前下载文件。

您需要等待;最好的方法是从 stdout 和/或 stderr 读取直到 EOF。

我认为这些读取将被阻塞,但由于在它们完成之前您无事可做,所以应该没问题。我相信 EOF 看起来像一个空字符串:""。