Shell脚本监控Linux资源(CPU、内存、磁盘)超过阈值邮件告警

#!/bin/bash
#
yum install -y sendEmail
yum install -y bc

Item=测试环境
Host=`/usr/bin/hostname`
Ip=`ip a | grep 'inet'|awk -F '[ ]' '{print $6}' | grep 24`
Cpu=`top -n1 | fgrep "Cpu(s)" | tail -1 | awk -F ' ' '{ print $2 }'`
KMem=`top -n1 | fgrep "KiB Mem" |tail -l | awk -F ' ' '{ print $8 }'`
ZKMem=`top -n1 | fgrep "KiB Mem" |tail -l | awk -F ' ' '{ print $4 }'`
BFBMem=$(printf "%.3f" `echo "scale=3;$KMem*100/$ZKMem"|bc`)
SMem=`top -n1 | fgrep "KiB Swap"  |tail -l| awk -F ' ' '{ print $5 }'`
ZSMem=`top -n1 | fgrep "KiB Swap" |tail -l| awk -F ' ' '{ print $3 }'`
#BFBKMem=`$(printf "%d%%" $((a*100/b)))`
DEV=`df -hP | grep '^/dev/*' | cut -d' ' -f1 | sort`

for I in $DEV
do dev=`df -Ph | grep $I | awk '{print $1}'`
size=`df -Ph | grep $I | awk '{print $2}'`
used=`df -Ph | grep $I | awk '{print $3}'`
free=`df -Ph | grep $I | awk '{print $4}'`
rate=`df -Ph | grep $I | awk '{print $5}'`
mount=`df -Ph | grep $I | awk '{print $6}'`
#内存检测
echo -e "$I:\tsize:$size\tused:$used\tfree:$free\trate:$rate\tmount:$mount"
F=`echo $rate | awk -F% '{print $1}'`
#if内阈值可以根据需求自己改
if [ $F -ge 90 ];then
    /usr/local/bin/sendEmail -f 发送邮箱地址([email protected]) -t 接收邮箱地址([email protected]) -s 邮箱服务地址(smtp.163.com) -u ''$Item' 系统资源监控' -o message-content-type=html -o message-charset=utf8 -xu 发送邮箱地址([email protected]) -xp '发送邮箱授权码,写在引号内' -m "$Host $Ip <br> [Disk Used] $mount disk used $rate <br> [Cpu Used] Cpu Used in $Cpu % <br> [KiB Mem Used] KiB Mem Used $BFBMem %" -o tls=no
fi
done
#CPU检测
if [ $(echo "$Cpu > 50"|bc) -eq 1 ];then
    /usr/local/bin/sendEmail -f 发送邮箱地址([email protected]) -t 接收邮箱地址([email protected]) -s 邮箱服务地址(smtp.163.com) -u ''$Item' 系统资源监控' -o message-content-type=html -o message-charset=utf8 -xu 发送邮箱地址([email protected]) -xp '发送邮箱授权码,写在引号内' -m "$Host $Ip <br> [Disk Used] $mount disk used $rate <br> [Cpu Used] Cpu Used in $Cpu % <br> [KiB Mem Used] KiB Mem Used $BFBMem %" -o tls=no
fi
#内存检测
echo $BFBMen
if [ `echo "$BFBMem > 95" | bc` -eq 1 ];then
    /usr/local/bin/sendEmail -f 发送邮箱地址([email protected]) -t 接收邮箱地址([email protected]) -s 邮箱服务地址(smtp.163.com) -u ''$Item' 系统资源监控' -o message-content-type=html -o message-charset=utf8 -xu 发送邮箱地址([email protected]) -xp '发送邮箱授权码,写在引号内' -m "$Host $Ip <br> [Disk Used] $mount disk used $rate <br> [Cpu Used] Cpu Used in $Cpu % <br> [KiB Mem Used] KiB Mem Used $BFBMem %" -o tls=no
fi

邮件结果在这里插入图片描述

发布了63 篇原创文章 · 获赞 3 · 访问量 1417

猜你喜欢

转载自blog.csdn.net/weixin_41772761/article/details/104000757