MySQL主從複製狀態監控及微信告警mysql
shell腳本實現當MySQL主從狀態異常時,觸發微信告警sql
1. 設置主從監控腳本shell
vi /opt/scripts/mysql/check_repl_status.shapi
#!/bin/bashbash
host='' # Slave 機器微信
user='' # mysql 賬號(能執行show slave status便可,不須要太大的權限)curl
passwd='' # mysql 密碼ide
_msgBodys()url
{spa
local int AppID=0
local UserID=$1
local Msg="$2"
cat << EOF
{
"touser": "${UserID}",
"msgtype": "text",
"agentid": "${AppID}",
"text": {
"content": "${Msg}"
},
"safe": "0"
}
EOF
}
_sendMsgs()
{
CropID='' #微信公衆號ID
Secret='' #微信公衆號Secret
GURL="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${CropID}&corpsecret=${Secret}"
Gtoken=$(/usr/bin/curl -s -G $GURL | grep -Po "(?<=access_token\W{3})[\w-]+")
PURL="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${Gtoken}"
/usr/bin/curl -s -k --data-ascii "$(_msgBodys "$1" "$2")" $PURL
}
num=`/opt/mysql/bin/mysql -u$user -p$passwd -h$host -e 'show slave status\G' |grep -E "Slave_IO_Running:|Slave_SQL_Running:"|awk '{print $2}'|grep -c Yes`
#檢查主從是否存在
if [ ! $num ]
then
msgs="Conn lost with mysql"
logtime=`date "+%Y-%m-%d %H:%M:%S"`
send_msg="XXX MySql Slave鏈接狀態\n${msgs}\n檢查時間:${logtime}"
#發送給全部人
_sendMsgs "@all" "$send_msg"
#狀態不全爲yes
elif [ $num -lt 2 ]
then
msgs=`/opt/mysql/bin/mysql -u$user -p$passwd -h$host -e 'show slave status\G' |grep -E "Master_Host:|Slave_IO_Running:|Slave_SQL_Running:"|sed s/[[:space:]]//g`
logtime=`date "+%Y-%m-%d %H:%M:%S"`
send_msg="XXX MySql主從複製狀態\n${msgs}\n檢查時間:${logtime}"
#發送給全部人
_sendMsgs "@all" "$send_msg"
fi
2. 設置crontab定時任務
*/5 * * * * /bin/bash /opt/scripts/mysql/check_repl_status.sh &>/dev/null 2>&1