我正在使用 Paramiko 从我的本地机器连接到 SFTP 服务器并从远程路径下载 txt 文件。我能够成功连接,也可以打印远程路径和文件,但我无法在本地获取文件。我可以打印file_path
和file_name
,但无法下载的所有文件。下面是我正在使用的代码:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname, username=username, password=password, port=port)
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'
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 在评论中所暗示的那样)。
请参阅使用 Paramiko 在 Python 中匹配通配符的 SFTP 服务器上的列表文件。
旁注:不要使用AutoAddPolicy
. 这样做你会失去安全感。请参阅Paramiko“未知服务器”。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句