备份log检查,自动邮件

/ 测试开发 / 0 条评论 / 1406浏览
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os
import smtplib
import datetime
from email.mime.text import MIMEText
from email.utils import formataddr

def get_today():
    day = datetime.date.today()
    strtmp = [str(day.year), '-', '%02d'%(day.month), '-', str(day.day)]
    strtoday = ''.join(strtmp)
    return strtoday+'-0250'

def checkLog():
    logFile = '/home/bitbuckt-backup/backupdate/log/atlassian-sbc-%s.log'%(get_today())
    print(logFile+"\n")
    if not os.path.exists(logFile):
        print("log not exist\n")
    with open(logFile,'r') as fd:
        lines = fd.readlines()

    flag = True
    for line in lines:
        if 'Failed' in line:
            flag = False;
            break
    if flag == True:
       print("back success!\n")
    else:
       print(str(mail()) + "\n")

def mail():
    msgFrom = '[email protected]'  # 发件人邮箱账号
    msgPasswd = '***'  # 发件人邮箱授权码
    msgTo = '[email protected]'  # 收件人邮箱账号
    msgCo = ''  # 抄送邮箱账号

    ret = True

    msg = MIMEText("备份失败", 'plain', 'utf-8')
    msg['From'] = formataddr(["xx", msgFrom])  # 括号里的对应发件人邮箱昵称、发件人
邮箱账号
    msg['To'] = formataddr(["a", msgTo])  # 括号里的对应收件人邮箱昵称、收件人邮箱账>号
    msg['Subject'] = "【报警】%s"%(get_today())  # 邮件的主题,也可以说是标题
    try:
        server = smtplib.SMTP("smtp.partner.outlook.cn", 587)
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login(msgFrom, msgPasswd)  # 括号中对应的是发件人邮箱账号、邮箱密码
        server.sendmail(msgFrom, msgTo.split(',')+ msgCo.split(','),msg.as_string())
        server.quit()  # 关闭连接
    except Exception as e:  # 如果 try 中的语句没有执行,则会执行下面的 ret=False
        print(e)
        ret = False
    return ret

checkLog()