本文目的:当分区空间大于70%时,通过自定义的清理命令进行清理日志等缓存文件。
一:脚本展示
#!/bin/bash
#scriptName: clearlog_grant70.sh
#doing:* * * * * cd /opt/yunwei/script/ && /bin/bash clearlog_grant70.sh
value=70
nodename=`hostname`
nodeip=`hostname -i`
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
cd /var/log/supervisor && find ./* -mmin +30 |grep log | xargs truncate -s 0k
}
#钉钉发送告警函数 start ...
dingSendFunc(){
echo $1 $2 $3 $4 $5 $6
url="https://oapi.dingtalk.com/robot/send?access_token=xx"
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
二:添加计划任务
#磁盘空间大于70%时清理日志
* * * * * /bin/bash -x /opt/yunwei/script/clearlog_grant70.sh
三:钉钉通知
完!