在python中使用sftp从远程路径获取文件到本地目录

编程入门 行业动态 更新时间:2024-10-23 05:50:55
本文介绍了在python中使用sftp从远程路径获取文件到本地目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试从远程路径获取文件到我的本地目录.当我执行代码时,出现错误.如下所述.

I am trying to get files from remote path to my local dir. When i am executing the code i am getting an error. as described below.

import paramiko import SSHLibrary from stat import S_ISDIR server, username, password = ('Remote ID', 'root', 'root') ssh = paramiko.SSHClient() paramiko.util.log_to_file("ssh.log") ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(server, username=username, password=password) ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('ls') print "output", ssh_stdout.read() #Reading output of the executed command error = ssh_stderr.read() #Transfering files to and from the remote machine sftp = ssh.open_sftp() print sftp.getcwd() print sftp.get_channel() print sftp.listdir("/home") sftp.get("/home","C:\\Users\\ShareM\\Desktop") #---> facing problem here sftp.close() ssh.close()

错误:-

Traceback (most recent call last): File "C:\Users\ShareM\Desktop\Automotive\devlopment\sshtesting\src\sshtest.py", line 36, in <module> sftp.get("/home","C:\\Users\\ShareM\\Desktop") File "build\bdist.win32\egg\paramiko\sftp_client.py", line 637, in get IOError: [Errno 13] Permission denied: 'C:\\Users\\ShareM\\Desktop'

需要帮助.

推荐答案

问题在于 sftp.get() 旨在传输单个文件而不是目录.因此,要下载整个目录,您应该获取其中的文件列表并单独下载:

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")

更多推荐

在python中使用sftp从远程路径获取文件到本地目录

本文发布于:2023-10-27 23:25:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534841.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路径   文件   目录   python   sftp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!