script/调用备份集检查工具并发邮件/SendCheckBackupReport.py

90 lines
2.5 KiB
Python

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import smtplib
import subprocess
import shutil
import os
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
from datetime import datetime
"""
执行备份集检查,将检查结果发送邮件
使用方法:
1.先手动确认backupCheckTool.jar运行无问题
2.将本脚本和backupCheckTool.jar放在同一个目录中
3.修改邮箱的收发件人地址
4.执行脚本
"""
#公共的
now=os.path.dirname(os.path.abspath(__file__))
week = str(datetime.now().isocalendar()[1])
file_path=os.path.join(now,"report.txt")
file_name_week="report" + week + ".txt"
file_week_path=os.path.join(now,file_name_week)
#检查工具
checktool=os.path.join(now,"backupCheckTool.jar")
if not os.path.exists(checktool):
assert False,u'backupCheckTool.jar not found,please check it!!'
def send_mail():
# 发件人
sender = 'mh@unamail.com'
# 接收邮件,可以发给多人
receivers = ['mh@unamail.com']
# 邮件主体
msg = MIMEMultipart()
# 正文
#文本内容太多了,不放了。
#with open(file_path, "r") as f: # 打开文本
# msgdata = f.read()
msgdata=""
message = "{0}周,备份集检测已完成,检测内容将附件\n{1}".format(
week, msgdata)
msg.attach(MIMEText(message, 'plain', _charset="utf-8"))
# 发送者
msg['From'] = Header(sender, 'utf-8')
# 接收者
msg['To'] = Header(receivers[0], 'utf-8')
# 主题
subject = '【长期任务】备份集检查-W{0}'.format(week)
msg['Subject'] = Header(subject, 'utf-8')
# 附件信息
att = MIMEText(open(file_week_path, 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="{}"'.format(
file_name_week)
msg.attach(att)
try:
smtpObj = smtplib.SMTP('10.10.110.102')
smtpObj.sendmail(sender, receivers, msg.as_string())
print("邮件发送成功")
except smtplib.SMTPException:
print("Error: 无法发送邮件")
def main():
#删除之前的文件
if os.path.exists(file_path):
os.remove(file_path)
#运行检查工具
commdline = ['java', '-jar', '-Dusername=unadba', '-Dpassword=1223Bc@2008', 'backupCheckTool.jar']
recode=subprocess.call(commdline)
#处理检查结果
shutil.copy2(file_path,file_week_path)
#发邮件
send_mail()
if __name__ == '__main__':
main()