這篇文章將為大家詳細(xì)講解有關(guān)怎樣利用python 發(fā)送MySQL慢日志郵件,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
創(chuàng)新互聯(lián)公司專業(yè)為企業(yè)提供高密網(wǎng)站建設(shè)、高密做網(wǎng)站、高密網(wǎng)站設(shè)計(jì)、高密網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁(yè)設(shè)計(jì)與制作、高密企業(yè)網(wǎng)站模板建站服務(wù),十余年高密做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。
一 需求
因?yàn)殚_發(fā)針對(duì)某系統(tǒng)做穩(wěn)定性建設(shè),需要對(duì)數(shù)據(jù)庫(kù)系統(tǒng)的慢日志進(jìn)行審計(jì),檢查優(yōu)化。和開發(fā)溝通選擇定期發(fā)送慢查詢到開發(fā)的郵箱的方式,每日匯總,然后一起評(píng)估 優(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)每小時(shí)將slow log 進(jìn)行分割,關(guān)于如何切割,各位可以思考一下。
關(guān)于怎樣利用python 發(fā)送MySQL慢日志郵件就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。