1. 程式人生 > 實用技巧 >shell指令碼監控mysql的狀態實現微信告警

shell指令碼監控mysql的狀態實現微信告警

1 註冊企業微信

參考 https://www.cnblogs.com/leomei91/p/7479562.html
註冊完成之後,需要找到:在告警中會用到

CropID="wx94e73cbe7c7dxxx" #填入企業ID值
Secret="Gf7KChFAh9Vw9AYXcAKp8WgSwJHCoNmPk5xxx"

2 具體指令碼內容

注意,腳本里的兩項要改成自己企業微信裡的值





#!/bin/bash

#監控mysql程序和連線數

host="127.0.0.1"
user="root"
passwd="mima"
port="3306"
order_mysql="/usr/bin/mysql"
hostip=`/usr/sbin/ifconfig eth0 | grep 'inet' | awk '{print $2}'`
connummax=151 # 最大連線數
name="麥芒test-mysql"
#process=`ps -ef |grep mysqld|grep -v grep|wc -l`
port=`sudo /usr/sbin/lsof -i:3306|grep -i listen|wc -l`
log_file=/tmp/waring.log
info="$info"
# 微信告警函式
function wechat(){
           msg="\\n${hostip}:$info \\n"${msg}
          CropID="wx94e73cbe7c7xxx"  #填入企業ID值
          Secret="Gf7KChFAh9Vw9AYXcAKp8WgSwJHCoNmPk5tbQaxxx"  #填入認證密碼
          GURL="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$CropID&corpsecret=$Secret"
          # 獲取token
          Gtoken=$(/usr/bin/curl -s -G $GURL | awk -F\" '{print $10}')
          PURL="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$Gtoken"
          body='{
          "touser": "@all",
          "msgtype": "text",
          "agentid": 1,
          "text":{
             "content":"故障:'$msg'"
               },
          "safe":0,
           "enable_id_trans": 0,
           "enable_duplicate_check": 0,
           "duplicate_check_interval": 1800
          }'
          /usr/bin/curl --data-ascii "$body" $PURL >>$log_file 2>&1

}


if   [ $port -ne 0 ] ;then
        echo "mysql is running" 
        # 檢視連線數
    CRONNECTEB=`$order_mysql -u$user -p$passwd -h$host -e "show status;" 2>/dev/null |grep Threads_connected|awk '{print $2}'`
    echo $CRONNECTEB
    #if [ 10 -ge 1 ];then
    if [ $CRONNECTEB -ge $connummax ];then
        info="mysql連線數過多"
        wechat  #呼叫微信告警
        echo  $name $CRONNECTEB |mailx -s "mysql連線數過多" [email protected]
    else
        
        info="mysql 連線數正常"
         
        echo "mysql 連線數正常"
    fi
else    
        info="mysql異常停止"
        wechat
        echo "mysql is shutdown![$(date "+%Y-%m-%d %H:%M:%S")]"|mailx -s "mysql異常停止" [email protected]
fi



最終效果如圖: