nagios监控mysql主从状态
看了网上很多mysql主从监控的,大部分都是shell的,就算是python的,也是在python下跑shell语句。我写了一个python的监控脚本,用到了mysqldb这个包。脚本如下:
[root@SSAVL2734 libexec]# cat check_mysql_formal.py #!/usr/bin/python import MySQLdb import sys import MySQLdb.cursors #coding:utf-8 if len(sys.argv) != 5: print len(sys.argv) print "Usage: %s [host port user passwd]" % sys.argv[0] sys.exit(1) else: host2 = sys.argv[1] port2 = sys.argv[2] user2 = sys.argv[3] passwd2 = sys.argv[4] conn=MySQLdb.connect(host=host2,port=3306,user=user2,passwd=passwd2,cursorclass=MySQLdb.cursors.DictCursor) cur= conn.cursor() cur.execute(r'show slave status') data=cur.fetchall() print data io=data[0]['Slave_IO_Running'] sql=data[0]['Slave_SQL_Running'] Seconds_Behind_Master=data[0]['Seconds_Behind_Master'] #print data[0] #print Seconds_Behind_Master #print type(Seconds_Behind_Master) #data= dict(zip(keys,data[0])) if sql == 'No' or io == 'No': print 'mysql replication is critical,please contact MYSQL DBA immediately' sys.exit(2) else: print 'replication is OK' sys.exit(0)
我看很多人都是用mysql的root跑show slave status这句话,测试是没问题,在生产环境运行还是有很大风险。这里我们新建一个监控账户,赋予能够查看复制情况的权限:
mysql> grant replication client on *.* to 'nagios'@'%' identified by 'nagios';
mysql> flush privileges;
验证是否生效:
[root@SSAVL2521 libexec]# mysql -h 10.90.**.* -unagios -pnagios -e "show slave status\G"
host port user passwd分别对应服务器名 端口号 账户 密码。
执行结果如下:
[root@SSAVL2734 libexec]# python check_mysql_formal2.py 10.90.**.* 3306 nagios nagios
replication is OK