原创

Linux中使用shell脚本监控服务器CPU、磁盘、内存使用情况

对于我们运维同学来说,都比较关注我们服务器的运行状况,而我们不可能时刻盯着服务器,所以我们就得考虑写个shell脚本定时去监控服务器的运行状况。
对于cup和内存,我们经常使用top命令来查看其使用情况,但是看起来还是费劲,磁盘利用率我们可以使用df -h 来查看。

下面我们针对这CPU、磁盘、内存使用情况来写个shell脚本监控

1、监控CPU脚本

#!/bin/bash
#
CPU_us=$(vmstat | awk '{print $13}' | sed -n '$p')
CPU_sy=$(vmstat | awk '{print $14}' | sed -n '$p')
CPU_id=$(vmstat | awk '{print $15}' | sed -n '$p')
CPU_wa=$(vmstat | awk '{print $16}' | sed -n '$p')
CPU_st=$(vmstat | awk '{print $17}' | sed -n '$p')

CPU1=`cat /proc/stat | grep 'cpu ' | awk '{print $2" "$3" "$4" "$5" "$6" "$7" "$8}'`
sleep 5
CPU2=`cat /proc/stat | grep 'cpu ' | awk '{print $2" "$3" "$4" "$5" "$6" "$7" "$8}'`
IDLE1=`echo $CPU1 | awk '{print $4}'`
IDLE2=`echo $CPU2 | awk '{print $4}'`
CPU1_TOTAL=`echo $CPU1 | awk '{print $1+$2+$3+$4+$5+$6+$7}'`
CPU2_TOTAL=`echo $CPU2 | awk '{print $1+$2+$3+$4+$5+$6+$7}'`
IDLE=`echo "$IDLE2-$IDLE1" | bc`
CPU_TOTAL=`echo "$CPU2_TOTAL-$CPU1_TOTAL" | bc`
#echo -e "IDLE2:$IDLE2\nIDLE1:$IDLE1\nCPU2:$CPU2_TOTAL\nCPU1:$CPU1_TOTAL"
#echo -e        "IDLE:$IDLE\nCPU:$CPU_TOTAL"
RATE=`echo "scale=4;($CPU_TOTAL-$IDLE)/$CPU_TOTAL*100" | bc | awk '{printf "%.2f",$1}'`

echo -e "us=$CPU_us\tsy=$CPU_sy\tid=$CPU_id\twa=$CPU_wa\tst=$CPU_st"
echo "CPU_RATE:${RATE}%"
CPU_RATE=`echo $RATE | cut -d. -f1`
#echo   "CPU_RATE:$CPU_RATE"
if      [ $CPU_RATE -ge 90 ]
then    echo "CPU告警:CPU使用率已经超过90%!"
        ps aux | grep -v USER | sort -rn -k3 | head
fi

CPU监控执行结果


2、监控磁盘脚本

#!/bin/bash
#
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 [ $F -ge 90 ];then
    echo "$mount 磁盘告警:磁盘利用率超过90%!"
else
    echo "磁盘利用率良好"
fi
done

磁盘监控执行结果


3、监控内存脚本

#!/bin/bash
#
total=$(free -m | sed -n '2p' | awk '{print $2}')
used=$(free -m | sed -n '2p' | awk '{print $3}')
free=$(free -m | sed -n '2p' | awk '{print $4}')
shared=$(free -m | sed -n '2p' | awk '{print $5}')
buff=$(free -m | sed -n '2p' | awk '{print $6}')
cached=$(free -m | sed -n '2p' | awk '{print $7}')
rate=`echo "scale=2;$used/$total" | bc | awk -F. '{print $2}'`
echo -e "total\tused\tfree\tshared\tbuffer\tavailable"
echo -e "${total}M\t${used}M\t${free}M\t${shared}M\t${buff}M\t${cached}M\nrate:${rate}%"
if    [ $rate -ge 80 ]
then    echo "Memory内存告警:内存使用率超过80%!"
    ps aux | grep -v USER | sort -rn -k4 | head
fi
内存监控执行结果

本文链接地址:http://www.ysxbohui.com/article/185

正文到此结束