Shell腳本監控MySQL主從狀態

分享一個Linux下,監控MySQL主從狀態及配合企業微信機器人報警的Shell腳本
SLAVE_IP:爲監控的主機IP
USER:爲msyql用戶
PASSWORD:爲mysql密碼
WHEREIS_MYSQL:爲mysql命令路徑
WEBHOOK:爲企業微信機器人Webhook地址
wx():爲企業微信機器人函數
Check_Mysql_Slave():爲監控腳本主函數mysql

#! /bin/bash
#
source /etc/profile
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

SLAVE_IP=`ip add | grep inet | grep brd | awk -F / '{print $1}' | awk -F " " '{print $2}' | awk 'NR==1'`
USER=monitor
PASSWORD=xxxxxx
TIME=`date`
WHEREIS_MYSQL=/opt/mysql/bin/mysql
WEBHOOK='https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=bb09197b-5ff6-4928-9872-xxxxxx'

wx(){
cat > $0.msg << EOF
curl '$WEBHOOK' \
   -H 'Content-Type: application/json' \
   -d '
   {
        "msgtype": "text",
        "text": {
            "content": "$1",
        }
   }'
EOF
sh $0.msg && rm -rf $0.msg
}


Check_Mysql_Slave()
{
    $WHEREIS_MYSQL -u$USER -p$PASSWORD -h$SLAVE_IP -e "select version();"  >/dev/null 2>&1
    if [  $? -ne 0 ];then
        echo "Mysql is stopped $DATE" >> /data/mysql/check.log
                ERROR="ERROR:Mysql-$SLAVE_IP cannot connect\n$TIME"
        wx "$ERROR"
    else
        #echo "1" >> /data/mysql/check.log
                IO_SQL_STATUS=`$WHEREIS_MYSQL -u$USER -p$PASSWORD -h$SLAVE_IP -e "show slave status \G" 2>/dev/null | awk '/Slave_.*_Running:/{print $1$2}'`
                for i in $IO_SQL_STATUS;do
                        THREAD_STATUS_NAME=${i%:*}
                        THREAD_STATUS=${i#*:}
                        if [ "$THREAD_STATUS" != "Yes" ];then
                                STATUS="ERROR:Mysql-$SLAVE_IP  $THREAD_STATUS_NAME status is $THREAD_STATUS!\n$TIME"
                echo "$STATUS" >> /data/mysql/check.log
                                wx "$STATUS"
                        fi
                done
     fi
}

Check_Mysql_Slave

最終報警效果以下:web

相關文章
相關標籤/搜索