#!/bin/bash
set -e
LogDir=/data/monitor/log
now_date=`date "+%Y-%m-%d %H:%M:%S"`
run_env()
{
#声明日志目录和需要监控的阀值
#CPU占用率,内存占用率,系统平均负载(根据系统cpu核数),硬盘空间
PoleCpu=90
PoleMem=90
PoleLod=2
PoleDsk=90
PolePid=`cat /proc/sys/kernel/pid_max`
#取系统相应的变量值
DATE=$(date +%Y%m%d)
TIME=$(date +"%H:%M:%S")
IP=$(/sbin/ifconfig ens32 |sed -n "2p"|awk '{print $2}')
LOAD=$(uptime|awk -F"load average:" '{print $2}'|awk -F, '{print $3}'|sed 's/ *//')
#MEM_total=$(free -m |grep "Mem" |awk {'print $2'})
#MEM_available=$(free -m |grep "Mem" |awk {'print $7'})
MEM=$(free -m |grep "Mem"| awk {'print ($2-$7)/$2*100'}|awk -F "[.]" {'print $1'})
#Cpud=$(top -b -n 1 | grep Cpu |awk -F "[,]" {'print $4'} |awk -F "[.]" {'print $1'})
CPUD=$(top -b -n 1 | grep Cpu |awk -F "[,]" {'print $4'} |awk -F "[.]" {'print (100-$1)'})
DISK=$(df|sed -e '1d;s/\/dev\///g'|awk '{printf "%s:%s\n",$1,$5}'|xargs)
OUTFILE=$LogDir/monitor$DATE.log
#将相关信息保存至OUTFILE中
echo ">>>>[$IP] $DATE $TIME
当前负载:$LOAD
当前内存使用率:$MEM%
当前cpu使用率:$CPUD%
硬盘空间:$DISK%
-----------------------<<<<" >> $OUTFILE
}
#检测CPU
CHECK_CPU()
{
CpuTest=$(echo "$CPUD>=$PoleCpu"|bc)
if [ $CpuTest -eq 1 ];then
message="当前CPU使用率达$CPUD%,超过指标$PoleCpu%--$now_date"
echo $message >> $LogDir/errlog-$DATE.log
echo $message
fi
}
#检测内存
CHECK_MEM()
{
MemTest=$(echo "$MEM>=$PoleMem"|bc)
if [ $MemTest -eq 1 ];then
message="当前内存使用率达$MEM%,超过指标$PoleMem%--$now_date"
echo $message >> $LogDir/errlog-$DATE.log
echo $message
fi
}
#检测负载
CHECK_LOAD()
{
LodTest=$(echo "$LOAD>=$PoleLod"|bc)
if [ $LodTest -eq 1 ];then
message="15分钟平均负载为$LOAD,超过指标$PoleLad--$now_date"
echo $message >> $LogDir/errlog-$DATE.log
echo $message
fi
}
#检测硬盘空间
CHECK_DISK()
{
DiskUse=$(df|sed -e '1d;s/%//g'|awk '{print $5}'|xargs)
for Dfree in $DiskUse ; do
if [ "$Dfree" -ge "$PoleDsk" ];then
message="硬盘使用空间超过指标$PoleIde%--$now_date"
echo $message >> $LogDir/errlog-$DATE.log
echo $message
break
fi
done
}
#检测最大连接数
CHECK_PID()
{
Pid_num=`ps -eLf |wc -l`
Pid_Test=$(echo "$Pid_num>=$PolePid"|bc)
if [ $Pid_Test -eq 1 ];then
message="当前最大连接数为:$Pid_num--$now_date 已超过系统最大值。。。"
echo $message >> $LogDir/errlog-$DATE.log
echo $message
fi
}
main()
{
run_env
CHECK_CPU
CHECK_MEM
CHECK_LOAD
CHECK_DISK
CHECK_PID
}
main
监控cpu内存磁盘脚本
最新推荐文章于 2024-06-29 15:12:35 发布