十年網(wǎng)站開發(fā)經(jīng)驗(yàn) + 多家企業(yè)客戶 + 靠譜的建站團(tuán)隊(duì)
量身定制 + 運(yùn)營維護(hù)+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
這篇文章將為大家詳細(xì)講解有關(guān)怎樣利用python 發(fā)送MySQL慢日志郵件,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

一 需求
因?yàn)殚_發(fā)針對某系統(tǒng)做穩(wěn)定性建設(shè),需要對數(shù)據(jù)庫系統(tǒng)的慢日志進(jìn)行審計(jì),檢查優(yōu)化。和開發(fā)溝通選擇定期發(fā)送慢查詢到開發(fā)的郵箱的方式,每日匯總,然后一起評估 優(yōu)化slow query 。
二 工具實(shí)現(xiàn)
mail.py 腳本
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# mail.py
import os.path
import time
import sys
import os
import json
import string
import random
import smtplib
import time
from datetime import date
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.Header import Header
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
mail_user="xxx@xxxx.com";
mail_pass="xxxxx";
mail_smtp_server="smtp.xxxxx.com";
mail_smtp_port= 25
def sendMail(contents,subject,attach,mail_to):
lTime=str(time.strftime('%Y%m%d_%H',time.localtime(time.time())))
msg = MIMEMultipart('related');
if subject=="":
subject='test';
msg['Subject'] = subject+" Time:"+ lTime;
msg['From'] = mail_user;
msg['To'] = ";".join(mail_to) ;
html="";
for cont in contents:
html = html+cont[0];
msgHtml = MIMEMultipart('alternative');
msgHtml.set_charset('UTF-8');
msgAtt = MIMEText(open(attach,'rb').read(),'base','gbk');
msgAtt["Content-Type"] = 'application/octet-stream'
msgAtt["Content-Disposition"] = 'attachment; filename="'+subject+'"'
msg.attach(msgAtt);
try:
smtp = smtplib.SMTP();
smtp.connect(mail_smtp_server,mail_smtp_port)
smtp.login(mail_user,mail_pass);
smtp.sendmail(mail_user,mail_to,msg.as_string());
smtp.close();
except Exception,e:
print str(e)
sendSlowlog.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import mail ##使用了上述腳本
import sys
import time
import os
import datetime
from datetime import date
from os.path import join, getsize
def sendSlowlog(subject_info,attach,mail_to):
size = os.path.getsize(attach)
if(size > 1):
mail.sendMail("",subject_info,attach,mail_to)
if __name__ == '__main__':
mail_to=["qilong.yangql@xxxx.com"]
lDate=str(time.strftime('%Y%m%d',time.localtime(time.time())))
lTime=str(time.strftime('%Y%m%d_%H',time.localtime(time.time())))
subject_info="Slowlog of DBname" + lTime
attach="/u01/my3306/log/slow_"+ lDate +"/slow.log."+lTime
sendSlowlog(subject_info,attach,mail_to)
注
本系統(tǒng)已經(jīng)每小時將slow log 進(jìn)行分割,關(guān)于如何切割,各位可以思考一下。
關(guān)于怎樣利用python 發(fā)送MySQL慢日志郵件就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。