1. 程式人生 > >Shell開發MySQL主從監控腳本

Shell開發MySQL主從監控腳本

抓取 tmp ifconf global 獲取 監控mysql one 郵件 slave

監控MySQL主從同步是否異常,如果異常,則發送短信或者郵件給管理員。 1)開發一個守護進程腳本每30秒實現檢測一次。
2)如果同步出現如下錯誤號(1158,1159,1008,1007,1062),則跳過錯誤。 階段3:
3)如果IO和SQL線程出現異常,則通知郵件給管理員

使用數組技術實現上述腳本(獲取主從判斷及錯誤號部分)

主從監控腳本如下:

#!/bin/bash
CODE=(
1158
1159
1008
1007
1062
2003
)
fun_Base(){
#1.定義變量

#1.1 抓取IP地址
IP=`ifconfig eth0 |awk ‘NR==2{print $2}‘`

#1.2 獲取slave IO和SQL狀態,Err代碼
My_SQL=`mysql -e "show slave status\G" |egrep "SQL_Running:" |awk ‘{print $NF}‘`
My_IO=`mysql -e "show slave status\G" |egrep "IO_Running:" |awk ‘{print $NF}‘`
My_CODE=`mysql -e "show slave status\G" |egrep "Last_IO_Errno:" |awk ‘{print $NF}‘`

#1.3 定時時間變量
Time=`date +%F-%H:%M:%S`

#1.4 定義log目錄
DIR=/tmp/slave_${Time}
Status_Log=$DIR/slave_status_${Time}.log
Check_log=$DIR/slave_check_${Time}.log
Erro_log=$DIR/slave_err_${Time}.log
#1.5 定義郵箱
Total="$IP slave status $Time"
Mail_Rec="[email protected]"

#2.將slave的狀態保存到log文件中
[ -d $DIR ] || mkdir $DIR -p
mysql -e "show slave status\G" >$Status_Log
}

#3.判斷slave狀態的錯誤代碼
fun_Status(){
RETVAL=0
for  ((i=0;i<${#CODE[*]};i++))
do
    if [ $My_CODE -eq ${CODE[i]}  ];then
       mysql -e "stop slave;" && RETVAL=$?
       [ $RETVAL -eq 0 ] && mysql -e "SET GLOBAL SQL_SLAVE_SKIP_COUNTER = 1;" && RETVAL=$?
       [ $RETVAL -eq 0 ] && mysql -e "start slave;" && RETVAL=$?
       [ $RETVAL -eq 0 ] && echo "slave errno code is successful." >$Erro_log
       [ $RETVAL -eq 0 ] && mail -s "$Total" $Mail_Rec <$Status_Log && mail -s "$Total" $Mail_Rec <$Erro_log
    fi
done
}

#4.判斷IO和SQL線程是否正常
fun_Check(){
  if [ "$My_SQL" == "Yes" -a "$My_IO" == "Yes" ];then
    echo "slave status is successful." 
    echo "slave status is successful." >$Check_log
    mail -s "$Total" $Mail_Rec <$Status_Log
    mail -s "$Total" $Mail_Rec <$Check_log
  else
    echo "slave status is failed."
    echo "slave status is failed." >>$Check_log
    mail -s "$Total" $Mail_Rec <$Status_Log
    mail -s "$Total" $Mail_Rec <$Check_log
 fi
}

#5.主體函數
main(){

while true
do
 fun_Base
 fun_Status
 fun_Check
 sleep 20
done
}

main

Shell開發MySQL主從監控腳本