[关闭]
@xiaoxiaowang 2018-03-17T16:06:41.000000Z 字数 1966 阅读 2512

通过shell脚本和企业微信实现报警功能(完整版)

运维 微信报警


接上篇
最终效果如图(GIF太大了 就截了两张图)
1.png
2.png

  1. #!/bin/sh
  2. expireTime=7200
  3. dbFile="db.json"
  4. corpid=xxx
  5. corpsecret=xxx
  6. touser="xxx"
  7. toparty="xxx"
  8. agentid="xxx"
  9. content="服务器快崩了,你还在这里吟诗作对?"
  10. # s 为秒,m 为 分钟,h 为小时,d 为日数
  11. interval=1s
  12. ## 发送报警信息
  13. sendMsg(){
  14. if [ ! -f "$dbFile" ];then
  15. touch "$dbFile"
  16. fi
  17. # 获取token
  18. req_time=`jq '.req_time' $dbFile`
  19. current_time=$(date +%s)
  20. refresh=false
  21. if [ ! -n "$req_time" ];then
  22. refresh=true
  23. else
  24. if [ $((current_time-req_time)) -gt $expireTime ];then
  25. refresh=true
  26. fi
  27. fi
  28. if $refresh ;then
  29. req_access_token_url=https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$corpid\&corpsecret=$corpsecret
  30. access_res=$(curl -s -G $req_access_token_url | jq -r '.access_token')
  31. ## 保存文件
  32. echo "" > $dbFile
  33. echo -e "{" > $dbFile
  34. echo -e "\t\"access_token\":\"$access_res\"," >> $dbFile
  35. echo -e "\t\"req_time\":$current_time" >> $dbFile
  36. echo -e "}" >> $dbFile
  37. echo ">>>刷新Token成功<<<"
  38. fi
  39. ## 发送消息
  40. msg_body="{\"touser\":\"$touser\",\"toparty\":\"$toparty\",\"msgtype\":\"text\",\"agentid\":$agentid,\"text\":{\"content\":\"$content\"}}"
  41. access_token=`jq -r '.access_token' $dbFile`
  42. req_send_msg_url=https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$access_token
  43. req_msg=$(curl -s -H "Content-Type: application/json" -X POST -d $msg_body $req_send_msg_url | jq -r '.errmsg')
  44. echo "触发报警发送动作,返回信息为:" $req_msg
  45. }
  46. loopMonitor(){
  47. echo 'loop'
  48. flag=`uptime | awk '{printf "%.2f\n", $11 "\n"}'`
  49. # 0.7 这个阈值可以视情况而定,如cpu核数为n,则可以设置为0.7 * n 具体视情况而定
  50. c=$(echo "$flag > 0.7" | bc)
  51. echo ">>>>>>>>>>>>>>>>>>`date`<<<<<<<<<<<<<<<<<<"
  52. free -m | awk 'NR==2{printf "Memory Usage: %s/%sMB (%.2f%%)\n", $3,$2,$3*100/$2 }'
  53. df -h | awk '$NF=="/"{printf "Disk Usage: %d/%dGB (%s)\n", $3,$2,$5}'
  54. uptime | awk '{printf "CPU Load: %.2f\n", $11 "\n"}'
  55. echo ">>>>>>>>>>>>>>>>>>end<<<<<<<<<<<<<<<<<<"
  56. if [ $c -eq 1 ];then
  57. sendMsg
  58. fi
  59. }
  60. while true; do
  61. loopMonitor
  62. sleep $interval
  63. done

让CPU达到100%的脚本

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

下周放线上试一试~

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

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注