sftp日志文件定时下载到本地文件 python 3

需求:

利用ssh协议和sftp服务,将日志文件夹里的文件同步到本地存储,检查时间-4至1
过滤条件:时间戳(20180101),与本地文件名全等

源码展示:

#!/usr/bin/env python
# -*- coding :uft-8 -*-
import paramiko
import os
import time
# 目录和文件名含中文直接爆炸...

def DownLoadFile(sftp, LocalFile, RemoteFile):  # 下载当个文件
    file_handler = open(LocalFile, 'wb')
    # print(file_handler)
    sftp.get(RemoteFile, LocalFile) # 下载目录中文件
    file_handler.close()
    return True


def DownLoadFileTree(sftp, LocalDir, RemoteDir):  # 下载整个目录下的文件

    if not os.path.exists(LocalDir):
        os.makedirs(LocalDir)
    for file in sftp.listdir(RemoteDir):
        Local = os.path.join(LocalDir, file)
        Remote = os.path.join(RemoteDir, file)
        if file.find(".") == -1:  # 判断是否是文件
            if not os.path.exists(Local):
                os.makedirs(Local)
            DownLoadFileTree(sftp, Local, Remote)
        else:  # 文件
            DownLoadFile(sftp, Local, Remote)
    return "complete"


def sftpFoder(sftp):
    ssh = serverConnect()
    stdin, stdout, stderr = ssh.exec_command('ls /home')
    res_list = stdout.readlines()[-1]

    # 本地文件local/远程目录remote
    local = r'..\\02\\OutPut\\%s\\%s\\' % (Ymd, res_list.strip()) # Windows文件夹
    remote = '/home/%s/' % res_list.strip()
    # 下载
    DownLoadFileTree(sftp, local, remote)


def serverConnect():
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname='10.1.22.31', port=22, username='root', password='huanu')
    return ssh


def LoginOS():
    # 登录系统
    transport = paramiko.Transport(('10.1.22.31', 22))
    transport.connect(username='root', password='huanu')
    # 链接sftp
    sftp = paramiko.SFTPClient.from_transport(transport)
    # 去下载筛选
    sftpFoder(sftp)


if __name__ == '__main__':
    # 获取时间/年月日时分秒
    YmdHMS = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))
    # 获取时间/年月日
    Ymd = time.strftime("%Y%m%d", time.localtime(time.time()))

    # 去登录系统
    LoginOS()
pg1

 

参考文献

Python实现SSH传输文件(sftp) - Sch01aR# - 博客园 https://www.cnblogs.com/sch01ar/p/8024744.html

python连接sftp下载文件及文件夹 - 天马行空的博客 - CSDN博客 https://blog.csdn.net/chenjl187/article/details/83858578

转载于:https://www.cnblogs.com/huanu/p/10161653.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值