一:本文目的
当服务器的分区使用量大于设定的阈值时,自动清理预先定义好的日志目录,并发送钉钉告警。
二:结果展示
三:过程概述
通过计划任务实现脚本每分钟执行一次,去检测分区使用率,当超过定义的阈值70%时就发出告警,并清理提前定义好的日志目录或文件。
四:过程细节
1.定义计划任务
[root@DFDJ-YZ01 logs]# crontab -l
#yunwei
01 10 * * * /bin/bash /opt/yunwei/scripts/clearlog_grant70.sh
[root@DFDJ-YZ01 logs]#
2.编写脚本
#!/bin/bash
#scriptName: clearlog_grant70.sh
#doing:* * * * * cd /opt/yunwei/script/ && /bin/bash clearlog_grant70.sh
value=70
nodename=`hostname`
nodeip=`ip addr |grep eth0 |grep in |awk '{print $2}' | awk -F '/' '{print $1}'`
time=`date '+%Y-%m-%d-%H:%M:%S'`
scriptname=$0
echo $scriptname
clearLogFunc(){
#start clear logs ...
##system
cd /var/log/ && ls |grep messages | xargs truncate -s 0k
cd /var/log/journal && find ./* -mmin +10 |grep journal | xargs truncate -s 0k
docker images |grep none |awk "{print $3}" |xargs docker rmi
docker container prune -f
docker image prune -f
docker volume prune -f
##project
cd /usr/local/nginx/logs/ && find . -type f -size +1000M |grep log | xargs truncate -s 0k
}
#钉钉发送告警函数 start ...
dingSendFunc(){
echo $1 $2 $3 $4 $5 $6
url="https://oapi.dingtalk.com/robot/send?access_token=xxxxx"
curl $url \
-H 'Content-Type: application/json' \
-d '{
"msgtype": "markdown",
"markdown":
{"title":"ECS服务器监控告警",
"text":"![screenshot](https://images.cnblogs.com/cnblogs_com/blogs/718800/galleries/2294157/o_230330085502_1.png) \n
**报警时间**: <font color=\"#0000FF\">'${1}' '${times}'</font>\n
**监控ip**: <font color=\"#0000FF\">'${2}-${3}' </font>\n
**磁盘空间使用率:** <font color=\"#FF0000\">'${4}%-${5}' </font> \n
> 来自脚本的监控--'${6}'
"
},
}'
}
#钉钉发送告警函数 end .
for i in ` df -h |grep -v Filesystem |awk '{print $5}'`;do
echo $i
a=`echo $i | sed 's/%//g' `
echo "new key is $a"
if [ $a -gt $value ];then
echo "$a >= $value, i will del logs ..."
b=`df -h |grep $i |awk '{print $NF}'`
dingSendFunc $time $nodename $nodeip $a $b $scriptname
clearLogFunc
else
echo " $a <= $value"
fi
done
3.测试一下效果(执行脚本)
cd /opt/yunwei/script/ && /bin/bash clearlog_grant70.sh
完!