一:本文目的

当服务器的分区使用量大于设定的阈值时,自动清理预先定义好的日志目录,并发送钉钉告警。


二:结果展示

运维自动化【当磁盘空间超过阈值时清理日志并发送告警】_bash

三:过程概述

     通过计划任务实现脚本每分钟执行一次,去检测分区使用率,当超过定义的阈值70%时就发出告警,并清理提前定义好的日志目录或文件。


四:过程细节

1.定义计划任务

[root@DFDJ-YZ01 logs]# crontab -l
#yunwei
01 10 * * *  /bin/bash /opt/yunwei/scripts/clearlog_grant70.sh
[root@DFDJ-YZ01 logs]# 
  • 1.
  • 2.
  • 3.
  • 4.

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
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.

3.测试一下效果(执行脚本)

cd /opt/yunwei/script/  && /bin/bash  clearlog_grant70.sh 
  • 1.


完!