#!/bin/bash
#Editor Y_ming
mt="/etc/motd"       #定义反馈信息文件,这个是ssh登录时显示message的文件!
#获取主机信息
hostname=$(uname -n)
ip=`ifconfig eth0 | awk '/inet addr/{print $2}'` #Defind ethX


while :              #定义一个循环定时执行监控脚本
do
sleep 15m       #每15分钟循环执行一次
echo "This is status of $hostname $ip from the monitor_script.">$mt
#CPU_monitor
load_15=$(uptime | awk '{print $(NF)}')    #获取当前主机15分钟平均负载
cpu_num=$(grep -c 'model name' /proc/cpuinfo)  #获取cpu核心数
vga=`echo "scale=2;a=$load_15/$cpu_num*100;if(length(a)==2) print("0");print("a")"| bc | awk -F. '{print $1}'`
#根据每核心的平均负载值反馈信息
if [ $vga -le 70 ] ;then
        echo "LoadAaverage=0."$vga",System running well.">>$mt
else
    if [ $vga -le 100 ] ;then
        echo "LoadAaverage=0."$vga",CPU will becoming full used.">>$mt
    elif [ $vga -le 120 ];then
        echo "LoadAaverage=0."$vga",CPU has over used">>$mt
    else
        echo "LoadAaverage=0."$vga",CPU has bigger over used.">>$mt
    fi
fi

#Memory_monitor
mem_free=`/usr/bin/free -m | awk '/Mem/{print $8=$4+$6+$7}'` #获取空闲内存值
mem_total=`/usr/bin/free -m | awk '/Mem/{print $2}'`       #获取总内存值
mem_used=`expr $mem_total - $mem_free`                     #计算已用内存
swap_total=`/usr/bin/free -m | awk '/Swap/{print $2}'`     #虚拟内存总值
swap_free=`/usr/bin/free -m | awk '/Swap/{print $4}'`      #空虚虚拟内存值  
swap_used=`expr $swap_total - $swap_free`                  #已经使用的虚拟内存

mem=`echo "scale=2;a=$mem_free/$mem_total*100;if(length(a)==2) print("0");print("a")"| bc | awk -F. '{print $1}'`
mem_used=`expr 100 - $mem`
#mem=15
swap=`echo "scale=2;a=$swap_free/$swap_total*100;if(length(a)==2) print("0");print("a")" | bc | awk -F. '{print $1}'`
#swap=20
if [ $mem -le "20" ];then
        echo "Mem has used $mem_used"M"/$mem_total"M" more than 80%,please check it.">>$mt
        if [ $swap -le 30 ];then
                echo "Swap has used $swap_used"M"/$swap_total"M" more than 70%,too.Please Check it right now.">>$mt
        fi
else
        echo "Mem has used $mem_used"%" that enough to running.">>$mt
fi

#Disk_monitor
#用一个循环判断所有挂载点的使用百分比,这个对lvm分区的需要修改执行
for i in $(df -h | grep / | awk  '{print $NF;}') #{\/,\/boot,\/dev\/shm,\/cdrom}
do
     num=$(/bin/df -h | grep -w $i | awk  '{print $(NF-1)}' | sed  's/%//g')
     #num=$(/bin/df -h | grep -w $poit | awk  '{print $(NF-1)}' | sed  's/%//g')
     if [ $num -gt 80 ]
        then
                echo "The Mountpoit $i will be full use, please check it.">>$mt
     fi
done
done