Python实现mysql主从监控脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import MySQLdb
import time
import mail163

now=time.strftime("%Y/%m/%d-%H:%M:%S",time.localtime())

class Mydb(object):
def __init__ (self,host,user,port,passwd,sock):
self.host=host
self.user=user
self.port=port
self.passwd=passwd
self.sock=sock
try:
self.db=MySQLdb.connect(host=self.host,user=self.user,port=self.port,passwd=self.passwd,unix_socket=self.sock)
except:
print "cann't connect to mysql server %s %s "%(self.host,self.port)
else:
self.cursor=self.db.cursor()
def get_slave(self):
self.cursor.execute(' show slave status ;')
slave=self.cursor.fetchall()
return slave
def check_status (self):
slave=self.get_slave()
if (slave[0])[10]!='Yes' or (slave[0])[11]!='Yes':
return 'stop'
else:
return 'running'
def close(self):
self.cursor.close()
def main ():
db=Mydb('localhost','root',3306,'JD#mysql87##','/var/lib/mysql/mysql.sock')
status=db.check_status()
print status
if status=='stop':
mail163.mail('64.88 slave down at %s'%(now))
db.close()
if __name__=='__main__':
main()