FTP上有系统的登录日志,日志是三台服务器传上去的,日志名称一致并且名称用日期命名,日志放在不同的文件夹下面。该脚本每天早上8点半去FTP下载日志。希望该文档可以帮助你。

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import time
import datetime
from ftplib import FTP
import logging
import os
logger=logging.getLogger()
logger.setLevel(logging.DEBUG)
fh=logging.FileHandler('logs.txt',mode='a')
formatter = logging.Formatter('%(asctime)s[line:%(lineno)d]-%(levelname)s: %(message)s')
fh.setFormatter(formatter)
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)
if not os.path.exists('download'):
      os.makedirs('download')
def ftp_connect():
    try:
        ftp_server = '127.0.0.1'  
        username = 'www'  # 用户名
        password = 'password'  # 密码
        ftp = FTP()
        ftp.connect(ftp_server, 21)
        ftp.login(username, password)
    except Exception as e:
        logger.error("FTP连接失败 %s"%e)
    else:
        return ftp
def download_file(filename,localname):
    ftp = ftp_connect()
    if ftp:
        if not os.path.exists(localname):
            logger.info("开始下载%s"%(filename))
            try:
                ftp.nlst(filename)
            except Exception as e:
                logger.error("%s文件不存在"%filename)
            else:
                try:
                    bufsize = 1024
                    fp = open(localname, 'wb')
                    ftp.retrbinary('RETR ' + filename, fp.write, bufsize)
                    fp.close()
                    ftp.quit()
                    logger.info("下载%s成功"%filename)
                except Exception as f:
                    logger.error("下载%s失败"%filename)
h=8
m=30
while True:
    yesterday=(datetime.datetime.now()-datetime.timedelta(days=1)).strftime("%Y-%m-%d")
    yesterday2=(datetime.datetime.now()-datetime.timedelta(days=1)).strftime("%Y%m%d")
    log='login.log_%s.log'%(yesterday)
    file=['/logs/101/%s'%log,'/logs/102/%s'%log,'/logs/103/%s'%log]
    for i in file:
        local="download/"+i.split('/')[-2]+"_"+i.split('/')[-1]
        download_file(i,local)
    while True:
        now = datetime.datetime.now()
        if now.hour == h and now.minute == m:
            break
        else:
            time.sleep(20)
            # logger.info("正常运行")
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐