我正在使用Paramiko从本地计算机连接到SFTP服务器,并从远程路径下载txt文件。我能够建立成功的连接,还可以打印远程路径和文件,但是我无法在本地获取文件。我可以打印file_path
和file_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))
我可以从file_path
语句中看到file_name
和print
,如下所示,但是在对多个文件使用ftp.get时出现错误。我可以通过在源和目标上对名称进行硬编码来复制单个文件。
file_path = '/home/blahblah/abc.txt'
file_name = 'abc.txt'
file_path = '/home/blahblah/def.txt'
file_name = 'def.txt'
我看到下载了一个文件,然后出现以下错误:
FileNotFoundErrorTraceback(最近一次通话结束)
错误跟踪:
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'
答案 0 :(得分:2)
readlines
不会从行中删除换行符。因此,如您在回溯中所见,您正在尝试创建一个名为abc.txt\n
的文件,这在许多文件系统上是不可能的,并且主要不是您想要的。
修剪file_path
中的尾随新行:
for file_path in stdout.readlines():
file_path = file_path.rstrip()
file_name = file_path.split('/')[-1]
# ...
尽管您可以省去很多麻烦,但是如果您使用了纯SFTP解决方案,而不是通过执行远程find
命令对其进行破解(这是非常脆弱的解决方案,如@CharlesDuffy的评论所暗示) )。
请参见List files on SFTP server matching wildcard in Python using Paramiko。
旁注:请勿使用AutoAddPolicy
。您
这样做会失去安全性。参见Paramiko "Unknown Server" 。