Shell脚本监控CPU、内存和硬盘利用率
February 3, 2015
在linux 下如何使用shell脚本来监控系统的cpu,内存和硬盘的使用率呢。请参考下面的脚本。
1、监控CPU利用率(通过vmstat工具)
#!/bin/bash if [ `uname` != "Linux" ];then echo "check os not linux." exit 1 fi which vmstat &>/dev/null if [ $? -ne 0 ];then echo "vmstat command no found, please install procps package." exit 1 fi 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'` #等待I/0完成 cpu_sum=$(($cpu_us+$cpu_sy)) cpu_info() {echo "CPU_Sum : $cpu_sum% ( CPU_Use:${cpu_us}% , CPU_System:${cpu_sy}% )" echo "CPU_Idle : ${cpu_id}%"<br />echo "CPU_Wait : ${cpu_wa}"} #cpu_info;<br />if [ $cpu_sum -ge 90 ];then echo "CPU utilization $cpu_sum." | mail -s "CPU Monitor" baojingtongzhi@163.com fi
2、监控内存利用率
#!/bin/bash which bc &>/dev/null if [ $? -ne 0 ];then echo "bc command no found, Please install bc package." exit 1 fi Date=`date +%F" "%H:%M` IP=`ifconfig eth0 | awk '/inet addr/ {print $2}' | cut -d: -f2` Total=`free -m | grep Mem | awk '{print $2}'` Use=`free -m | awk '/buffers\// {print $NF}'` Free=$(($Total-$Use)) Total_conv=`echo "scale=2;$Total/1024" | bc | awk '{print $1"G"}'` #通过bc计算,保留小数点后两位(scale) if [ $Free -lt 200 ];then Content=`echo -e "Date : $Date \nHost : $IP \nTotal : ${Total_conv} \nUse : ${Use}M \nFree : ${Free}M"` echo "$Content" | mail -s "Memory Monitor" baojingtongzhi@163.com fi
3、监控磁盘利用率
#!/bin/bash Date=`date +%F" "%H:%M` IP=`ifconfig eth0 | awk '/inet addr/ {print $2}' | cut -d: -f2` Total=`fdisk -l | grep "Disk /dev/sd[a-z]" |awk '{print $2$3"GB"}' |sed 's/:/=/'` Disk_Use=`df -h |awk '{print $1"="$5}' | sed '1d' | sed 's/%//g'` for i in $Disk_Use do A=`echo $i |awk -F'=' '{print $2}'` if [ $A -gt 8 ];then echo -e "Date : $Date \nHost : $IP \nTotal : $Total \nProblem : Part Use ${i}%" | mail -s "Disk Monitor" aaa@163.com fi done
0 Comments