python - 要从 sftp 服务器下载文件夹,它会在本地目录中下载文件夹,但是当我给出特定的文件路径时,它会显示错误
问题描述
我附上了下面的代码,请给任何一个解决方案。
当我给出远程路径时,例如:/file/ICC1/log.txt
和本地路径:E:\abc
然后显示错误
raise IOError(errno.ENOENT, text) IOError: [Errno 2] 没有这样的文件
import os
import pysftp
from stat import S_IMODE, S_ISDIR, S_ISREG
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
sftp=pysftp.Connection('192.168.X.X', username='username',password='password',cnopts=cnopts)
def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
for entry in sftp.listdir(remotedir):
remotepath = remotedir + "/" + entry
localpath = os.path.join(localdir, entry)
mode = sftp.stat(remotepath).st_mode
if S_ISDIR(mode):
try:
os.mkdir(localpath,mode=777)
except OSError:
pass
get_r_portable(sftp, remotepath, localpath, preserve_mtime)
elif S_ISREG(mode):
sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)
remote_path=input("enter the remote_path: ")
local_path=input("enter the local_path: ")
get_r_portable(sftp, remote_path, local_path, preserve_mtime=False)
解决方案
get_r_portable
(取自Linux的Python pysftp get_r 在 Linux 上运行良好,但在 Windows 上运行良好)用于下载文件夹。请注意,它以remotedir
参数中给出的远程目录列表开头:sftp.listdir
。
所以你不能用它来下载单个文件。
要下载单个文件,请使用 simple SFTPClient.get
(将远程和本地文件的路径作为参数提供):
remotepath = '/remote/path/file.txt'
localpath = r'c:\local\path\file.txt'
sftp.get(remotepath, localpath)
推荐阅读
- reactjs - 如何在 onChange 后清除 Material-ui 中的自动完成输入?
- powershell - PowerShell 导出不在特定组中的 AD 用户 + 属性
- c++ - 如何更改包含二维数组c ++的最高值和最低值的列
- python - 在我通过在 GUI 上点击“x”关闭 opencv 图像窗口后,终端冻结
- azure - 多域通配符 SSL 映射多个 Azure 应用服务应用
- vala - 如何克服有关 functioni 参数在 vala 中为 const 的警告?
- javascript - React:检测多个组件外的点击
- asp.net - 如何在 asp.net 中使用 gmail api
- flutter - 如何知道文本中每一行的字符串长度?
- windows - 使用 Powershell 运行 .bat 脚本时避免“不被识别为内部或外部命令”