脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python实现自动下载sftp文件

python实现自动下载sftp文件

2021-10-16 09:47Jepson2017 Python

这篇文章主要为大家详细介绍了python实现自动下载sftp文件,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了python实现自动下载sftp文件的具体代码,供大家参考,具体内容如下

实现功能:利用python自动连接sftp,并下载sftp中指定目录下的所有目录及文件

  • 系统环境:centos7
  • python版本:python3
  • 使用模块包:paramiko ,若未安装,可使用 pip install paramiko 进行安装

需求实例:sftp中的文件如下

python实现自动下载sftp文件

将sftp根目录中的所有文件下载到本地 /data/test 目录中

实现代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!/usr/bin/python
# coding=utf-8
 
import paramiko
import os
 
def sftp_download(sftp,localDir,remoteDir):
    if remoteDir.find(".") == -1:#判断远程目录参数是否是目录,前提是远程的文件名中都包含扩展名,否则此方法不可用
        for file in sftp.listdir(remoteDir):
            remoteDirTmp=os.path.join(remoteDir,file)
            localDirTmp=os.path.join(localDir,file)
            sftp_download(sftp,localDirTmp,remoteDirTmp)
    else:
        localPath=localDir.rpartition("/")[0]
        if not os.path.exists(localPath):
            os.makedirs(localPath)
        print("download file:",remoteDir)
        try:
            sftp.get(remoteDir,localDir)
        except Exception as e:
            print('download exception:',e)
    
    
if __name__ == '__main__':
    host = '192.168.149.128'#sftp主机
    port = 22 #端口
    username = 'sftp' #sftp用户名
    password = '123456'
    localDir = '/data/test'#本地文件或目录
    remoteDir = '/'#远程文件或目录
    sf = paramiko.Transport((host,port))
    sf.connect(username = username,password = password)
    sftp = paramiko.SFTPClient.from_transport(sf)
    sftp_download(sftp,localDir,remoteDir)
    sf.close()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/d1240673769/article/details/106295184

延伸 · 阅读

精彩推荐