基於Python實現自動慢查詢分析,郵件自動發送

由兩個程序文件組成,第一個程序實現慢查詢分析,文件上傳html

#!/usr/local/python27/bin/python2.7
from fabric.api import *
from fabric.context_managers import *
from fabric.contrib.console import confirm
import sys
import os
import time
import datetime

sdir = '/alidata/server/mysql/data/'
ddir = '/root/'

env.user='root'

env.roledefs = {
    'master_db':['192.168.1.2'],
    'slave_db':['192.168.1.3'],
    'quliao_db':['192.168.1.4']
}

env.passwords = {
    'root@192.168.1.2:22':'123456',
    'root@192.168.1.3:22':'123456',
    'root@192.168.1.4:22':'123456'
}


#慢查詢分析函數,這個函數會調用服務端本地的工具分析慢查詢,以後會清空慢查詢文件。
def my_slow(ori_log,save_log,result_log):
    run('cp '+sdir+ori_log+' '+save_log)
    run('/usr/local/bin/mysqlsla -lt slow '+ddir+save_log+' -sort c_sum -top 10 >'+'/root/'+result_log)
    run('echo '+''+'>'+sdir+ori_log)

#用於下載服務端分析好的慢查詢文件保存到本地新建的目錄中
def my_get(fname):
    with lcd('/alidata/slow_log'):
        dname = time.strftime('%Y%m%d',time.localtime(time.time()))

        with cd('/root/'):
            get(fname,dname+'/')

#定義文件刪除函數,接受兩個參數,用於刪除拷貝出來的慢查詢文件和分析以後的慢查詢文件。
def remove(f1,f2):
    with cd('/root'):
        run('rm -f '+f1+' '+f2 )

#在客戶端機器建立一個以當前日期爲名稱的文件夾,用於保存分析好的慢查詢文件
@runs_once
def mk_dir():
    with lcd('/alidata/slow_log'):
        dname = time.strftime('%Y%m%d',time.localtime(time.time()))
        local('mkdir '+dname)


@roles('slave_db')
def sdb():
    print ("run slave db pro")
    run("ls /alidata/server/mysql/data")
    my_slow('slow.log','mysql-r-'+time.strftime('%Y%m%d',time.localtime(time.time()))+'.log','mysql-read-'+time.strftime('%Y%m%d',time.localtime(time.time()))+'.log')
    my_get('mysql-read-'+time.strftime('%Y%m%d',time.localtime(time.time()))+'.log')
    remove('mysql-r-'+time.strftime('%Y%m%d',time.localtime(time.time()))+'.log','mysql-read-'+time.strftime('%Y%m%d',time.localtime(time.time()))+'.log')

@roles('master_db')
def mdb():
    print ('run master db pro')
    run("ls /alidata/server/mysql/data")
    my_slow('AY131008162509536ef1Z-slow.log','mysql-w-'+time.strftime('%Y%m%d',time.localtime(time.time()))+'.log','mysql-write-'+time.strftime('%Y%m%d',time.localtime(time.time()))+'.log')
    my_get('mysql-write-'+time.strftime('%Y%m%d',time.localtime(time.time()))+'.log')
    remove('mysql-w-'+time.strftime('%Y%m%d',time.localtime(time.time()))+'.log','mysql-write-'+time.strftime('%Y%m%d',time.localtime(time.time()))+'.log')

@roles('quliao_db')
def ldb():
    print ('run quliao db pro')
    run("ls /alidata/server/mysql/data")
    my_slow('slow.log','mysql-q-'+time.strftime('%Y%m%d',time.localtime(time.time()))+'.log','mysql-quliao-'+time.strftime('%Y%m%d',time.localtime(time.time()))+'.log')
    my_get('mysql-quliao-'+time.strftime('%Y%m%d',time.localtime(time.time()))+'.log')
    remove('mysql-q-'+time.strftime('%Y%m%d',time.localtime(time.time()))+'.log','mysql-quliao-'+time.strftime('%Y%m%d',time.localtime(time.time()))+'.log')

def deploy():
    mk_dir()
    execute(sdb)
    execute(mdb)
    execute(ldb)
#最後這裏是調用客戶端本地的郵件發送程序把剛剛抓回來的慢查詢日誌以郵件附件的形式發送給管理員。
    local('/root/tuchao/sendma.py')



第二個程序負責把分析好的日誌以郵件附件的形式發送給管理員
python

#!/usr/local/python27/bin/python2.7
# coding=utf8
import smtplib
import time
import datetime
from email.mime.text import MIMEText
from email import encoders
from email.header import Header
from email.utils import parseaddr, formataddr
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase

from_addr = 'tuchao@mail.admin.net'
password = '111111'
smtp_server = '114.234.116.2'
to_addr = ['123456@qq.com','1234567@qq.com']

slow_log_path = '/alidata/slow_log/'+time.strftime('%Y%m%d',time.localtime(time.time()))+'/'


def _format_addr(s):
    name,addr = parseaddr(s)
    return formataddr((Header(name,'utf-8').encode(),addr.encode('utf-8') if isinstance(addr, unicode) else addr))

#須要將多個對象組合起來,在這裏構建一個MIMEMultipart對象。 
msg = MIMEMultipart()

msg['From'] = _format_addr(u'來自運維技術XX <%s>' % from_addr)
msg['To'] = _format_addr(u'管理員 <%s>' % to_addr)
msg['Subject'] = Header(u'MySQL慢查詢日誌', 'utf-8').encode()

msg.attach(MIMEText('<html><body><h3>mysql-read:從庫讀慢查詢</h3>' +
    '<p><h3>mysql-write:主庫讀寫慢查詢</h3></p>'
    '<p><h3>mysql-quliao:外部程序庫讀寫慢查詢</h3></p>'
    '<p><img src="cid:1"></p>' +
    '</body></html>', 'html', 'utf-8'))


with open(slow_log_path+'mysql-read-'+time.strftime('%Y%m%d',time.localtime(time.time()))+'.log','rb') as f:
    mime = MIMEBase('text/plain','txt',filename='mysql-read-'+time.strftime('%Y%m%d',time.localtime(time.time()))+'.log')
    mime.add_header('Content-Disposition','p_w_upload',filename='mysql-read-'+time.strftime('%Y%m%d',time.localtime(time.time()))+'.log')
    mime.add_header('Content-ID','<0>')
    mime.add_header('X-Attachment-Id','0')
    mime.set_payload(f.read())
    encoders.encode_base64(mime)
    msg.attach(mime)

with open(slow_log_path+'mysql-write-'+time.strftime('%Y%m%d',time.localtime(time.time()))+'.log','rb') as f:
    mime = MIMEBase('text/plain','txt',filename='mysql-write-'+time.strftime('%Y%m%d',time.localtime(time.time()))+'.log')
    mime.add_header('Content-Disposition','p_w_upload',filename='mysql-write-'+time.strftime('%Y%m%d',time.localtime(time.time()))+'.log')
    mime.add_header('Content-ID','<0>')
    mime.add_header('X-Attachment-Id','0')
    mime.set_payload(f.read())
    encoders.encode_base64(mime)
    msg.attach(mime)

with open(slow_log_path+'mysql-quliao-'+time.strftime('%Y%m%d',time.localtime(time.time()))+'.log','rb') as f:
    mime = MIMEBase('text/plain','txt',filename='mysql-quliao-'+time.strftime('%Y%m%d',time.localtime(time.time()))+'.log')
    mime.add_header('Content-Disposition','p_w_upload',filename='mysql-quliao-'+time.strftime('%Y%m%d',time.localtime(time.time()))+'.log')
    mime.add_header('Content-ID','<0>')
    mime.add_header('X-Attachment-Id','0')
    mime.set_payload(f.read())
    encoders.encode_base64(mime)
    msg.attach(mime)

with open('/alidata/slow_log/aamy.jpg','rb') as f:
    mime = MIMEBase('p_w_picpath','jpg',filename='aamy.jpg')
    mime.add_header('Content-Disposition','p_w_upload',filename='aamy.jpg')
    mime.add_header('Content-ID','<1>')
    mime.add_header('X-Attachment-Id','0')
    mime.set_payload(f.read())
    encoders.encode_base64(mime)
    msg.attach(mime)

server = smtplib.SMTP(smtp_server,25)
server.set_debuglevel(0)
server.login(from_addr,password)
server.sendmail(from_addr,to_addr,msg.as_string())
server.quit()

構造一個郵件對象就是一個Messag對象mysql

構造一個MIMEText對象,就表示一個文本郵件對象sql

構造一個MIMEImage對象,就表示一個做爲附件的圖片api

要把多個對象組合起來,就用MIMEMultipart對象運維

MIMEBase能夠表示任何對象python2.7

相關文章
相關標籤/搜索