ITPub博客

【工具】利用python 发送MySQL 慢日志邮件

Linux操作系统 作者:18141908802 时间:2018-06-29 09:23:39 0 删除 编辑
一 需求
    因为开发针对某系统做稳定性建设,需要对数据库系统的慢日志进行审计,检查优化。和开发沟通选择定期发送慢查询到开发的邮箱的方式,每日汇总,然后一起评估 优化slow query 。

二 工具实现
mail.py  脚本
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # mail.py
  4. import os.path
  5. import time
  6. import sys
  7. import os
  8. import json
  9. import string
  10. import random
  11. import smtplib
  12. import time
  13. from datetime import date
  14. from email.mime.multipart import MIMEMultipart
  15. from email.mime.text import MIMEText
  16. from email.mime.image import MIMEImage
  17. from email.Header import Header
  18. from email.MIMEText import MIMEText
  19. from email.MIMEMultipart import MIMEMultipart

  20. mail_user="xxx@xxxx.com";
  21. mail_pass="xxxxx";
  22. mail_smtp_server="smtp.xxxxx.com";
  23. mail_smtp_port= 25

  24. def sendMail(contents,subject,attach,mail_to):
  25.     lTime=str(time.strftime('%Y%m%d_%H',time.localtime(time.time())))
  26.     msg = MIMEMultipart('related');
  27.     if subject=="":
  28.         subject='test';
  29.     msg['Subject'] = subject+" Time:"+ lTime;
  30.     msg['From'] = mail_user;
  31.     msg['To'] = ";".join(mail_to) ;
  32.     html="";
  33.     for cont in contents:
  34.         html = html+cont[0];
  35.     msgHtml = MIMEMultipart('alternative');
  36.     msgHtml.set_charset('UTF-8');
  37.     msgAtt = MIMEText(open(attach,'rb').read(),'base','gbk');
  38.     msgAtt["Content-Type"] = 'application/octet-stream'
  39.     msgAtt["Content-Disposition"] = 'attachment; filename="'+subject+'"'
  40.     msg.attach(msgAtt);

  41.     try:
  42.         smtp = smtplib.SMTP();
  43.         smtp.connect(mail_smtp_server,mail_smtp_port)
  44.         smtp.login(mail_user,mail_pass);
  45.         smtp.sendmail(mail_user,mail_to,msg.as_string());
  46.         smtp.close();
  47.     except Exception,e:
  48.         print str(e)
 sendSlowlog.py
 
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import mail ##使用了上述脚本
  4. import sys
  5. import time
  6. import os
  7. import datetime

  8. from datetime import date
  9. from os.path import join, getsize

  10. def sendSlowlog(subject_info,attach,mail_to):
  11.     size = os.path.getsize(attach)
  12.     if(size > 1):
  13.        mail.sendMail("",subject_info,attach,mail_to)


  14. if __name__ == '__main__':
  15.    mail_to=["qilong.yangql@xxxx.com"]
  16.    lDate=str(time.strftime('%Y%m%d',time.localtime(time.time())))
  17.    lTime=str(time.strftime('%Y%m%d_%H',time.localtime(time.time())))
  18.    subject_info="Slowlog of DBname" + lTime
  19.    attach="/u01/my3306/log/slow_"+ lDate +"/slow.log."+lTime
  20.    sendSlowlog(subject_info,attach,mail_to)


   本系统已经每小时将slow log 进行分割,关于如何切割,各位可以思考一下。 



请登录后发表评论 登录
全部评论

注册时间:2017-01-16

  • 博文量
    79
  • 访问量
    18722