python MySQL-Slave从服务器状态检测脚本

时间:2022-09-19 01:54:57
#!/bin/bash
mysql -e "show slave status\G" > mysql_status.txt
array=($(egrep 'Slave_IO_Running|Slave_SQL_Running|Seconds_Behind_Master' mysql_status.txt))
if [[ "${array[1]}" == 'Yes' && "${array[3]}" == 'Yes' ]]
then
        if "${array[5]}" -eq 0 ]
        then
        echo "MySQL slave running OK!"
        else
        echo "MySQL slave is behind master ${array[5]} seconds"
        fi
else
        echo "MySQL slave sync make error"
        mail -s "MySQL-Slave Error on `uname -n`" 44850823@qq.com
fi
 
 
=====================

# -*- coding: utf-8 -*
#! /usr/bin/env python
#
#sudo easy_install fabric
#sudo easy_install paramiko
#fab -f mysql.py check
#[利用Python监测MySQL主从状态](http://hypocritical.blog.51cto.com/3388028/1680778)
#[Python fabric远程自动部署简介](http://lovesoo.org/python-fabric-yuan-cheng-zi-dong-bu-shu-jian-jie.html)
#[自动化运维工具Fabric - 密码管理](http://segmentfault.com/a/1190000000497630)

from fabric.api import *
from fabric.colors import *
from fabric.context_managers import *
from fabric.contrib.console import confirm
import string
import smtplib
import paramiko

#错误日志
#paramiko.util.log_to_file("filename.log")

#client ip
env.user='root'
env.hosts=[
'192.168.60.7',
'192.168.60.61',
]
#env.password='xx'
env.port='22'
#env.user='root'
#env.password='xx'
env.passwords={
'root@192.168.60.7:22':"password",
'root@192.168.60.61:22':"password",
}

#env.mysql_port = '3306'
@task
def check():
slave_ip = run("ip add|grep global")
for ip in env.hosts:
if ip in slave_ip:
slave_ip = ip
slave_io = run("mysql -ustatus -pxx -h"+slave_ip+" -e 'show slave status\G'|grep Slave_IO_Running:|awk '{print $2}'")
slave_sql = run("mysql -ustatus -pxx -h"+slave_ip+" -e 'show slave status\G'|grep Slave_SQL_Running:|awk '{print $2}'")
if slave_io.find('Yes')>=0 and slave_sql.find('Yes') >= 0:
pass
else:
HOST = "smtp.163.com"
SUBJECT = "MySQL Master-Slave Warning . "
TO = "xx@qq.com"
FROM = "xx@163.com"
text = "%-20s MySQL Master-Slave status : down" % slave_ip
BODY = string.join((
"From: %s" % FROM,
"To: %s" % TO,
"Subject: %s" % SUBJECT ,
"",
text
), "\r\n")
server = smtplib.SMTP()
server.connect(HOST,"25")
server.starttls()
server.login("xx@163.com","password")
server.sendmail(FROM, [TO], BODY)
server.quit()