通過shell指令碼和企業微信實現報警功能(完整版)

爆米花機槍手發表於2018-03-18

最終效果如圖(GIF太大了 就截了兩張圖)
1.png

2.png

#!/bin/sh

expireTime=7200

dbFile="db.json"

corpid=xxx
corpsecret=xxx

touser="xxx"
toparty="xxx"
agentid="xxx"
content="伺服器快崩了,你還在這裡吟詩作對?"

# s 為秒,m 為 分鐘,h 為小時,d 為日數  
interval=1s

## 傳送報警資訊
sendMsg(){
    if [ ! -f "$dbFile" ];then
            touch "$dbFile"
    fi

    # 獲取token
    req_time=`jq '.req_time' $dbFile`
    current_time=$(date +%s)
    refresh=false
    if [ ! -n "$req_time" ];then
            refresh=true
    else
            if [ $((current_time-req_time)) -gt $expireTime ];then
                refresh=true
            fi
    fi
    if $refresh ;then
        req_access_token_url=https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$corpid\&corpsecret=$corpsecret
        access_res=$(curl -s -G $req_access_token_url | jq -r '.access_token')

        ## 儲存檔案
        echo "" > $dbFile
        echo -e "{" > $dbFile
        echo -e "\t\"access_token\":\"$access_res\"," >> $dbFile
        echo -e "\t\"req_time\":$current_time" >> $dbFile
        echo -e "}" >> $dbFile

        echo ">>>重新整理Token成功<<<"
    fi 

    ## 傳送訊息
    msg_body="{\"touser\":\"$touser\",\"toparty\":\"$toparty\",\"msgtype\":\"text\",\"agentid\":$agentid,\"text\":{\"content\":\"$content\"}}"
    access_token=`jq -r '.access_token' $dbFile`
    req_send_msg_url=https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$access_token
    req_msg=$(curl -s -H "Content-Type: application/json" -X POST -d $msg_body $req_send_msg_url | jq -r '.errmsg')

    echo "觸發報警傳送動作,返回資訊為:" $req_msg    

}


loopMonitor(){
    echo 'loop'
    flag=`uptime | awk '{printf "%.2f\n", $11 "\n"}'`


    # 0.7 這個閾值可以視情況而定,如cpu核數為n,則可以設定為0.7 * n  具體視情況而定
    c=$(echo "$flag > 0.7" | bc)

    echo ">>>>>>>>>>>>>>>>>>`date`<<<<<<<<<<<<<<<<<<"
    free -m | awk 'NR==2{printf "Memory Usage: %s/%sMB (%.2f%%)\n", $3,$2,$3*100/$2 }'
    df -h | awk '$NF=="/"{printf "Disk Usage: %d/%dGB (%s)\n", $3,$2,$5}'
    uptime | awk '{printf "CPU Load: %.2f\n", $11 "\n"}'
    echo ">>>>>>>>>>>>>>>>>>end<<<<<<<<<<<<<<<<<<"

    if [ $c -eq 1  ];then
         sendMsg
    fi
}


while true; do
    loopMonitor
    sleep $interval
done

讓CPU達到100%的指令碼

for i in `seq 1 $(cat /proc/cpuinfo |grep "physical id" |wc -l)`; do dd if=/dev/zero of=/dev/null & done

歡迎提PR

CSDN:http://blog.csdn.net/qqhjqs?viewmode=list
部落格:http://vector4wang.tk/
簡書:https://www.jianshu.com/u/223a1314e818
Github:https://github.com/vector4wang
Gitee:https://gitee.com/backwxc

相關文章