34323 发表于 2016-8-5 09:27:28

python监控数据主从复制的脚本

#!/usr/bin/python
#-*- coding: UTF-8 -*-
#
#因登录权限问题,更改IP登录的方式,改为sock识别不同的数据库实例
#
import os
importMySQLdb
from email import encoders
from email.header import Header
from email.mime.text importMIMEText
from email.utils import parseaddr,formataddr
import smtplib

#check module
def check_status(socket,username,password,portnum):
      try:
                conn = MySQLdb.connect( host='localhost',user=username,passwd=password,port=portnum,unix_socket=socket)
                cursor = conn.cursor(MySQLdb.cursors.DictCursor)
                cursor.execute('show slave status;')
                res = cursor.fetchall()
                iostats=res.get('Slave_IO_Running')
                sqlstats=res.get('Slave_SQL_Running')
                last_error=res.get('Last_SQL_Error')
                rp = open('report.txt','w')
                if iostats != 'Yes':
                        rp.write('iostat:'+iostat+'\n')
                if sqlstats != 'Yes':
                        rp.write('sqlstat:'+sqlstat+'\n')
#               print iostats,sqlstats,last_error
                rp.close()
                cursor.close()
                conn.close()
      except MySQLdb.Error,e:
                print "Mysql Error %d: %s" %(e.args,e.args)


#
#mail module
def mailto(title,t):

#发送邮件函数,从文件t中读取内容,并发送给管理员

      def _format_addr(s):
                #格式化邮件信息头
                name,addr = parseaddr(s)
                returnformataddr((Header(name,'utf-8').encode(),addr))
      from_addr = '*********@126.com'
      password = '***********'
      to_addr = '*******@qq.com'
      smtp_server = 'smtp.126.com'
      msg = MIMEText(_text=open(t,'r').read(),_subtype='plain' ,_charset='utf-8')
      msg['From'] = _format_addr('数据库状态监控<%s>' % from_addr)
      msg['To'] = to_addr
      msg['Subject'] = Header(title ,'utf-8'.encode())
      try:
                server = smtplib.SMTP(smtp_server,25)
                server.starttls()
                server.set_debuglevel(0)
                server.login(from_addr,password)
                server.sendmail(from_addr,,msg.as_string())
                server.quit()
                return True
      except Exception,e:
                print str(e)
                return False

if __name__=='__main__':

      try:
                check_status('/home/data/mysql3309/mysql.sock','root','************',3309)
                er = os.path.getsize('./report.txt')
                if er != 0:
                        mailto('Slave-Status Of 192.168.1.204:3309','./report.txt')
      except Exception,e:
                print str(e)
#               with open('./report.txt','w') as f:
#                     f.write(str(e))
#                     mailto('check_error','./report.txt')


页: [1]
查看完整版本: python监控数据主从复制的脚本