因生产环境是MySQL主从,而有时从库挂掉,缺乏有效的监控。为了及时发现从库故障,所以简单写了个mysql从库检测脚本,并发邮件通知,有待完善。
其实思路很简单,查看MySQL主从状态应该都会,就是进入MySQL,然后show master status和show slave status G,然后我要做的其实就是通过脚本定时进入MySQL然后查看状态得到信息,再通过grep和awk对文本进行解析,然后关键的slave_sql_running、slave_io_running和last_error判断后,异常则发送邮件。
#!/bin/bash #copyright by hwb #check MySQL_Slave Status #crontab time 00:10 MYSQLPORT=`netstat -na|grep "LISTEN"|grep "3306"|awk -F[:" "]+ '{print $4}'` MYSQLIP=`ifconfig | grep inet |grep -v 'inet6'|grep -v '127.0.0.1'|awk -F ' ' '{print $2}'` STATUS=$(mysql -u root -pXXX -e "show slave statusG" | grep -i "running") IO_env=`echo $STATUS | grep IO | awk ' {print $2}'` SQL_env=`echo $STATUS | grep SQL | awk '{print $2}'` DATA=`date +"%y%m%d-%H:%M:%S"` if [ "$MYSQLPORT" == "3306" ] then echo "mysql is running" else mail -s "warn!server: $MYSQLIP mysql is down" huangwb@fslgz.com fi if [ "$IO_env" = "Yes" -a "$SQL_env" = "Yes" ] then echo "Slave is running!" else echo "####### $DATA #########">> /home/check_mysql_slave.log echo "Slave is not running!" >> /home/check_mysql_slave.log echo "Slave is not running!" | mail -s "warn!$MYSQLIP MySQL Slave is not running" huangwb@fslgz.com fi
输出结果:
停止mysql后:
设置定时任务
0 */5 * * * sh /home/scripts/mysql.sh