批量服務器硬件監控

#!/bin/bash
array=(`cat /usr/local/dsh/etc/hard.txt`)  //需要監控的服務器ip
disk_limit=80          //硬盤閥值
cpu_limit=80           //CPU閥值

mem_limit=80        //內存閥值

e_mail=‘[email protected]’       //報警郵件

function max(){       //求最大值函數
eval nums=($*)
max=0
for((i=0;i<${#nums[@]};i++))
do
  array_num=${nums[$i]}
  [ $array_num -gt $max ]&&max=$array_num
done
echo $max
}
function disk_info(){     //硬盤監控
for ((i=0;i<${#array[@]};i++));do
host=${array[$i]}
disk=(`dsh -r ssh -m $host -- df -Th|awk 'NR>1{print $6}'|awk -F % '{print $1}'`)  //得到各服務器硬盤使用
diskuse=`max ${disk[*]}`  //找出各服務器硬盤使用的最大值
if [ $diskuse -gt $disk_limit ]; then  //大於閥值報警
    disk_message="${host}硬盤使用率大於${disk_limit}%"
    `echo $disk_message|mail -s "${host}disk!" $e_mail`
    echo "disk: $disk_message"
fi

done
}

function mem_info(){   //內存監控
for ((x=0;x<${#array[@]};x++));do
host=${array[$x]}
mem_free=`dsh -r ssh -m $host --  cat /proc/meminfo | grep 'MemFree' | awk '{print $2}'`
mem_buff=`dsh -r ssh -m $host --  cat /proc/meminfo | grep 'Buffers' | awk '{print $2}'`
mem_cached=`dsh -r ssh -m $host --  cat /proc/meminfo| grep '^Cached' | awk '{print $2}'`
mem_free_total=`echo ${mem_free}+${mem_buff}+${mem_cached}|bc`
mem_total=`dsh -r ssh -m $host -- cat /proc/meminfo | grep MemTotal|awk '{print $2}'`
mem_use=$((100-${mem_free_total}*100/${mem_total}))
if [ $mem_use -gt $mem_limit ];then
    mem_message="${host}內存使用率爲:${mem_use}%"
    `echo $mem_message | mail -s "${host}memory${mem_use}%!" $e_mail`
    echo "$mem: {mem_message}"
 fi
done
}

function cpu_info(){     //cpu監控
for ((j=0;j<${#array[@]};j++));do
host=${array[$j]}
cpu_get1=`dsh -r ssh -m $host -- cat /proc/stat | grep 'cpu[0-9]*'|awk '{use+=$2+$3+$4;free+=$5+$6+$7+$8}END{print use,free}'`
sleep 8
cpu_get2=`dsh -r ssh -m $host -- cat /proc/stat | grep 'cpu[0-9]*'|awk '{use+=$2+$3+$4;free+=$5+$6+$7+$8}END{print use,free}'`
cpu_use=`echo $cpu_get1 $cpu_get2 |awk '{used=$3-$1;total=$3+$4-$2-$1;print used*100/total}'`
cpu_useexp=`echo $cpu_use/1+1|bc`
echo $cpu_useexp
if [ $cpu_useexp -gt $cpu_limit ]; then
   cpu_usepid=`ps aux|sort -nnk 3r|head -2|sed -e '1d'|awk '{print $3,$11}'`
   cpu_message="${host}cpu使用率爲:${cpu_use},進程名:`echo ${cpu_usepid}|awk '{print $2}'`,佔用:`echo ${cpu_usepid}|awk '{print $1}'`%"
   `echo $cpu_message | mail -s "${host}cpu${cpu_use}%!" $e_mail`
   echo "cpu: $cpu_message"
fi
done
}
echo `date`
disk_info
mem_info
cpu_info

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章