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

标签 python-2.7 sftp paramiko

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

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()旨在传输单个文件而不是目录。因此,要下载整个目录,您应该获取其中的文件列表并分别下载:

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-2.7 - 在python中使用sftp从远程路径获取文件到本地目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24427283/

相关文章:

sftp - 错误 : Connection timed out after 20 seconds of inactivity?

python - Paramiko SSHClient无法在远程计算机上执行整个shell脚本

python - 用于在 linux 中读取 ncdu 命令结果的 paramiko Python 模块

Python 通过 SSH 身份验证克隆私有(private) GitHub 存储库,无需访问 ssh 二进制文件(在 Azure Functions 下)

python - 从 Anaconda 运行 Python 时出现 ImportError : No module named sysconfig,

java - jep 在 java 中使用 scikit 模型

python - Ubuntu 加密主目录 | Errno 36 文件名太长

python - 从字符串中获取不在另一个列表中的单词列表

shell - Shell脚本中的SFTP错误处理

java - SFTP 连接器 DH key 错误