实时监控linux系统内存和硬盘,空间不足时发送邮件告警

创建脚本 free.sh

#!/bin/bash
 
#需求:实时监控本机内存和硬盘的剩余空间,剩余内存小于500M时、根剩余空间小于1000M时,发送报警邮件给管理员
 
#1.获取剩余内存
free_memory=`free -m |awk 'NR==2{print $4}'`
 
#2.获取剩余磁盘空间
free_hard=`df -BM |awk 'NR==6{print $4}'` |sed 's/M//'
 
#3.如果内存和硬盘空间达到阈值,发送邮件
if [ $free_memory -le 500 ];then
                #写邮件
                echo "当前可用内存是:$free_memoryM" >> /tmp/messages.txt
                echo "当前内存不足,请转进维护服务器" >> /tmp/messages.txt
 
                #发邮件
                mail -s "当前可用内存是$free_memotyM"  [email protected] < /tmp/messages.txt
fi
 
if [ $free_hard -le 1000 ];then
        #写邮件
        echo "当前可用硬盘是:$free_hardM" >> /tmp/messages.txt
        echo "当前硬盘空间不足,请抓紧时间维护" >> /tmp/messages.txt
 
        #发邮件
        mail -s "当前可用硬盘空间是$free_memotyM"  [email protected] < /tmp/messages.txt
fi

#邮件地址 配置为 [email protected],要提前配好。配置文件是/etc/mail.rc
将上述脚本加入定时任务,每3分钟运行一次

通过如下命令进入编辑定时任务的文件里: crontab -e
#t添加如下内容
*/3 * * * * bash /root/free.sh

你可能感兴趣的:(linux,chrome,运维)