在 Python 中使用 Paramiko 从远程命令列出的 SFTP 服务器下载文件

Downloading files from SFTP server listed by remote command with Paramiko in Python

我正在使用 Paramiko 从我的本地计算机连接到 SFTP 服务器并从远程路径下载 txt 文件。我能够成功连接,也可以打印远程路径和文件,但我无法在本地获取文件。我可以打印 file_pathfile_name 但无法下载所有文件。下面是我使用的代码:

import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect(主机名=主机名,用户名=用户名,密码=密码,端口=端口)

remotepath = '/home/blahblah'
pattern = '"*.txt"'
stdin,stdout,stderr = ssh.exec_command("find {remotepath} -name {pattern}".format(remotepath=remotepath, pattern=pattern))
ftp = ssh.open_sftp()
for file_path in stdout.readlines():
   file_name = file_path.split('/')[-1]
   print(file_path)
   print(file_name)
   ftp.get(file_path, "/home/mylocalpath/{file_name}".format(file_name=file_name))

我可以从 print 语句中看到 file_pathfile_name,但在对多个文件使用 ftp.get 时出错。我可以通过在源和目标上硬编码名称来复制单个文件。

file_path = '/home/blahblah/abc.txt'
file_name = 'abc.txt'
file_path = '/home/blahblah/def.txt'
file_name = 'def.txt'

我看到一个文件已下载,然后出现以下错误:

FileNotFoundErrorTraceback (most recent call last)

错误跟踪:

Traceback (most recent call last):  
File "<stdin>", line 1, in <module>
File "...anaconda3/lib/python3.6/site-packages/paramiko/sftp_client.py", line 769, in get
  with open(localpath, 'wb') as fl:
FileNotFoundError: [Errno 2] No such file or directory: 'localpath/abc.txt\n'

readlines 不会从行中删除换行符。因此,正如您在回溯中看到的那样,您正在尝试创建一个名为 abc.txt\n 的文件,这在许多文件系统上是不可能的,而且主要是,这不是您想要的。

Trim 来自 file_path 的尾随新行:

for file_path in stdout.readlines():
    file_path = file_path.rstrip()
    file_name = file_path.split('/')[-1]
    # ...

虽然你会省去很多麻烦,但如果你使用纯 SFTP 解决方案,而不是通过执行远程 find 命令来破解它(这是一个非常脆弱的解决方案,正如评论中所暗示的那样) @CharlesDuffy).

参见


旁注:不要使用 AutoAddPolicy。你 这样做会失去安全感。参见 Paramiko "Unknown Server"