#!/bin/bash # chkconfig: 2345 10 90 # description:监测linux服务器cpu、内存、磁盘 #cpu平均负载阀值 cpu_AVERAGE_LOAD=0.7 #剩余的最少警告的阀值 MIN_WARNING=20 #超过最多警告的阀值 MAX_WARNING=90 #监测cpu负载 monitor_cpu(){ #十五分钟平均负载值 load_quarter=`uptime | awk '{print $NF}'` #cpu内核数 cpu_num=`grep -c 'model name' /proc/cpuinfo` #cpu最大负载 cpu_load=${cpu_num} #报警的负载阀值 warning=$(echo ${cpu_load} \* ${cpu_AVERAGE_LOAD}|bc) if [ $(echo "${load_quarter} >= ${warning} "|bc) == 1 ] then #报警 warn 'cpu负载较大,请尽快处理' fi #监测cpu空闲比 cpu_idle=`top -b -n 1 | grep cpu | awk '{print $8}' |cut -f 1 -d .` if [ ${cpu_idle} -lt ${MIN_WARNING} ] then warn 'cpu占用较高请尽快处理' fi } #监测内存 monitor_memory(){ #总的内存 total=`free -m |grep 'Mem'|awk '{print $2}' ` #可用的内存 available=`free -m |grep 'Mem'|awk '{print $NF}'` #可用内存所占比例 rate=$(echo "scale=2;${available} / ${total} * 100"|bc) if [ $(echo "${rate} <= ${MIN_WARNING}"|bc) == 1 ] then warn '内存占用较大,请尽快处理' fi #监测Swap swap_total=`free -m|grep 'Swap'|awk '{print$2}'` swap_free=`free -m|grep 'Swap'|awk '{print$4}'` if [ ${swap_total} -gt 0 ] then swap_rate=$(echo "scale=2;${$swap_free} / ${swap_total}"|bc) if [ $(echo "${swap_rate} <= ${MIN_WARNING}"|bc) == 1 ] then warn '内存Swap剩余较少,请尽快处理' fi fi } #监测磁盘 monitor_disk(){ #过滤第一行 for i in `df -h |grep / |awk 'BEGIN {print 0} {print $5} END{print 0}'|cut -f 1 -d '%'` do if [ $(echo "${i} >= ${MAX_WARNING}"|bc) == 1 ] then warn '磁盘即将用完,请尽快处理' break fi done } #报警,发送邮件 warn(){ #发邮件 printf "`date +%Y%m%d%H%M%S`: `/usr/local/PHP5/bin/PHP /var/www/html/tools/PHPmailer/wangyi.PHP ${1}` \n" >> /var/log/monitorlog 2>&1 } #执行方法 monitor_cpu monitor_memory monitor_disk
2、配置每小时执行一次
0 */1 * * * /var/www/shell/monitor