getting a files from remote path to local dir using sftp in python

妖精的绣舞 提交于 2019-12-05 15:02:13

The problem is that sftp.get() is intended to transfer a single file not a directory. So to download entire directory you should get list of files in it and download them separately:

def download_dir(remote_dir, local_dir):
    import os
    os.path.exists(local_dir) or os.makedirs(local_dir)
    dir_items = sftp.listdir_attr(remote_dir)
    for item in dir_items:
        # assuming the local system is Windows and the remote system is Linux
        # os.path.join won't help here, so construct remote_path manually
        remote_path = remote_dir + '/' + item.filename         
        local_path = os.path.join(local_dir, item.filename)
        if S_ISDIR(item.st_mode):
            download_dir(remote_path, local_path)
        else:
            sftp.get(remote_path, local_path)


download_dir("/home","C:\\Users\\ShareM\\Desktop")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!