一、创建监控脚本

#!/bin/bash

#钉钉机器人Webhook地址
DINGTALK_WEBHOOK_URL="添加自己的钉钉机器人的Webhook地址"

#服务器ip地址
ip_addrs="172.17.140.189"

#监控CPU使用率
cpu_usage=$(top -b -n 1 | grep "Cpu(s)" | awk '{print $2 + $4}' | awk '{print int($1)}')
threshold=80  # 设定CPU使用率的阈值为80%
if [ $cpu_usage -gt $threshold ]; then
   message="服务器ip地址:$ip_addrs 
CPU警告: 当前使用率 $cpu_usage%"
   curl -s -H 'Content-Type: application/json' -d  "{\"msgtype\": \"text\", \"text\": {\"content\": \"$message\"}}" $DINGTALK_WEBHOOK_URL
fi

#监控内存使用率
mem_usage=$(free -m | grep Mem | awk '{print $3/$2 * 100.0}' | awk '{print int($1)}')
threshold=80  # 设定内存使用率的阈值为80%
if [ $mem_usage -gt $threshold ]; then
   message="服务器ip地址:$ip_addrs
内存警告: 当前使用率 $mem_usage%"
   curl -s -H 'Content-Type: application/json' -d "{\"msgtype\": \"text\", \"text\": {\"content\": \"$message\"}}" $DINGTALK_WEBHOOK_URL
fi

#监控磁盘使用率
disk_usage=$(df -h  | grep /dev/vda1 |awk '{print $5}'|awk '{print int($1)}')
threshold=80 # 设定磁盘使用率的阈值为80%
if [ $disk_usage -gt $threshold ]; then
   message="服务器ip地址:$ip_addrs
磁盘警告: 当前使用率 $disk_usage%"
   curl -s -H 'Content-Type: application/json' -d "{\"msgtype\": \"text\", \"text\": {\"content\": \"$message\"}}" $DINGTALK_WEBHOOK_URL
fi

二、设置crontab定时任务

####一分钟执行一次监控shell脚本
* * * * * /bin/bash  /root/monitor.sh >/dev/null &