问题描述
当我提供远程路径时,例如:/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,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
(取自 Python pysftp get_r from Linux works fine on Linux but not on Windows) 用于下载文件夹。请注意,它以 remotedir
参数中给出的远程目录列表开头:sftp.listdir
。
所以你不能用它来下载单个文件。
要下载单个文件,请使用简单的 SFTPClient.get
(为其提供远程和本地文件的路径作为参数):
remotepath = '/remote/path/file.txt'
localpath = r'c:\local\path\file.txt'
sftp.get(remotepath,localpath)