#!/bin/bash
#maximum ratio of memory usage
mem_quota=80
#maximum ratio of hard disk usage
hd_quota=80
#maximum ratio of cpu usage
cpu_quota=80
#time gap between two times fetching cpu status
time_gap=60
#generate report every 600 minutes
runtime_gap=600
#fetch the ratio of memory usage
#@return 1:if larger then #mem_quota;0:if less then $mem_quota
watch_memory()
{
mem_total=`cat /proc/meminfo | grep MemTotal | awk '{print $2}'`
mem_free=`cat /proc/meminfo | grep MemFree | awk '{print $2}'`
mem_usage=$((100-mem_free*100/mem_total))
if [ $mem_usage -gt $mem_quota ]
then
mem_message="at `date` :alarm !!! the memory usage is $mem_usage%!!!"
return 1
else
return 0
fi
}
#fetch the ratio of hard disk usage
#@return 1:if larger then #hd_quota;0:if less then $hd_quota
watch_hd()
{
hd_usage=`df|grep /dev/sda1 |awk '{print $5}'|sed 's/%//g'`
if [ $[hd_usage] -gt $[hd_quota] ]
then
hd_message="at `date`:alarm!!! the hard disk usage is $hd_usage%!!!"
return 1
else
return 0
fi
}
get_cpu_info()
{
cat /proc/stat |grep -i "^cpu[0-9]\+" | awk '{used+=$2+$3+$4;unused+=$5+$6+$7+$8} END{print used,unused}'
}
watch_cpu()
{
time_point_1=`get_cpu_info`
sleep $time_gap
time_potin_2=`get_cpu_info`
cpu_usage=`echo $time_point_1 $time_point_2 | awk '{used=$3-$1;total+=$3+$4-$1-$2;print used*100/total;}'`
if [ $cpu_usage > $cpu_quota ]
then
cpu_message="at `date`:alarm !!! the cpu usage is over $cpu_usage!!!"
return 1
else
return 0
fi
}
proc_cpu_top10() #获取cpu占用内存最高的10个进程
{
proc_busiest=`ps aux|sort -nk 3r|head -11`
}
while true ; do
watch_memory
if [ "$?" -eq "1" ]
then
report=$mem_message
echo $report>>report.txt
fi
watch_hd
if [ "$?" -eq 1 ]
then
report=$hd_message
echo $report>>report.txt
fi
watch_cpu
if [ "$?" -eq "1" ]
then
report=$cpu_message
echo $report>>report.txt
echo
proc_cpu_top10
report=$proc_busiest
echo $report>>report.txt
echo
fi
sleep $((runtime_gap-time_gap))
done