Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

python - To download the folder from sftp server, It downloading the folder in local directory but when i am giving particular file path then its showing error

I am attaching the below code please give the solution any one.

When I am giving the remote path such as: /file/ICC1/log.txt and local path : E:abc

Then it's showing error

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)
question from:https://stackoverflow.com/questions/65935222/to-download-the-folder-from-sftp-server-it-downloading-the-folder-in-local-dire

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The get_r_portable (taken from Python pysftp get_r from Linux works fine on Linux but not on Windows) is for downloading a folder. Note that it starts with a listing of a remote directory given in the remotedir parameter: sftp.listdir.

So you cannot use it to download a single file.

To download a single file, use simple SFTPClient.get (giving it paths to remote and local files as arguments):

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...