Monitoring mysql master-slave status script

1. mysql master-slave architecture construction

Reference link >> https://blog.csdn.net/m0_46674735/article/details/109597636

2. The basic script content is as follows

#!/bin/bash
IO=$(mysql -e "show slave status\G;" |awk '/Slave_IO_Running/{print $2}')
SQL=$(mysql -e "show slave status\G;" |awk '/Slave_SQL_Running/{print $2}')

DATE_TIME=$(date +%F_%T)
admin_mail=[email protected]
IP=$(ifconfig |awk '/broadcast/{print $2}')
if [ $IO != "Yes" -o $SQL != "Yes" ];then
    mail.py $admin_mail  "MySQL 警告!!!" "时间:$DATE_TIME  主机名:$HOSTNAME  主机地址:$IP  事件:Slave状态异常"
fi

Stop the mysql service of the main database

systemctl stop mariadb

Test script

sh check_slave.sh 

Receive the alert email successfully

Insert picture description here

3. The contents of the extended script are as follows

#!/bin/bash
while :
do
    IO=$(mysql -e "show slave status\G;" |awk '/Slave_IO_Running/{print $2}')
    SQL=$(mysql -e "show slave status\G;" |awk '/Slave_SQL_Running/{print $2}')
    LOG_FILE=/tmp/slave_check.log
    DATE_TIME=$(date +%F_%T)
    admin_mail=[email protected]
    IP=$(ifconfig |awk '/broadcast/{print $2}')
    if [ $IO != "Yes" -o $SQL != "Yes" ];then
        echo "$DATE_TIME $HOSTNAME Slave 同步状态异常" >> $LOG_FILE
        mail.py $admin_mail  "MySQL 警告!!!" "时间:$DATE_TIME  主机名:$HOSTNAME  主机地址:$IP  事件:Slave状态异常"
        num=1
        #监控slave状态是否恢复正常
        while [ $num -lt 15 ];do
            IO=$(mysql -e "show slave status\G;" |awk '/Slave_IO_Running/{print $2}')
            SQL=$(mysql -e "show slave status\G;" |awk '/Slave_SQL_Running/{print $2}')
            if [ $IO = "Yes" -a $SQL = "Yes" ];then
                echo "$DATE_TIME $HOSTNAME Slave 同步状态恢复正常" >> $LOG_FILE
                mail.py $admin_mail  "MySQL 通知" "时间:$DATE_TIME  主机名:$HOSTNAME  主机地址:$IP  事件:Slave状态恢复正常"
                break
            else
                let num++
            fi
            sleep 60
        done
    fi
    sleep 60
done

Stop the mysql service of the main database

systemctl stop mariadb

Test script

sh check_slave.sh 

Receive the alert email successfully

Insert picture description here

Restore the mysql service of the main database

systemctl start mariadb

Successfully received notification of state restoration

Insert picture description here

Guess you like

Origin blog.csdn.net/m0_46674735/article/details/112388006