要从sftp服务器下载文件夹,它会在本地目录中下载文件夹,但当我给出特定的文件路径时,它会显示错误

2024-04-26 04:24:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我附上下面的代码,请给任何一个解决方案

当我给出远程路径时,例如:/file/ICC1/log.txt 和本地路径:E:\abc

然后它显示错误

raise IOError(errno.ENOENT, text) IOError: [Errno 2] No such file

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)

Tags: pathimportgetosmodesftpentryportable
1条回答
网友
1楼 · 发布于 2024-04-26 04:24:41

get_r_portable(取自Python pysftp get_r from Linux works fine on Linux but not on Windows)用于下载文件夹。注意,它以remotedir参数中给出的远程目录列表开始:sftp.listdir

因此,您不能使用它下载单个文件

要下载单个文件,请使用简单的^{}(将远程和本地文件的路径作为参数):

remotepath = '/remote/path/file.txt'
localpath = r'c:\local\path\file.txt' 
sftp.get(remotepath, localpath)

相关问题 更多 >