您的位置:首页 > 运维架构

监控服务器cpu,mem,disk自动邮件报警,并将数据写入表中。

2014-07-07 17:27 761 查看
加入crontab 中,5分钟执行一次

*/5 * * * * /home/ymx/moniter.sh >> /home/ymx/moniter.log 2>&1

脚本如下

#!/bin/bash

##################

. /etc/profile

. ~/.bash_profile

##################

#for i in `/bin/ps -ef | grep moniter.sh | grep -v grep | awk '{print $2}'`;do

# /bin/kill -9 $i

#done

hostname kjw`/sbin/ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}' | tail -1 | cut -d. -f4`

#sleep 3

#while [ 0 ];do

maxcpu=80

maxmem=80

maxdisk=80

notice_mail="yuanmx@qq.com yuanmx@gmail.com"

function insert_log()

{

mysql -h*.*.*.* -u* -p* dbname << EOF

insert into moniter(insert_time,server_ip,cpu_used,cpu_model,cpu_num,mem_size,mem_used,disk_default_size,disk_default_used,disk_home_size,disk_home_used) values("$insert_time","$server_ip","$cpu_used","$cpu_model","$cpu_num","$mem_size","$mem_used","$disk_default_size","$disk_default_used","$disk_home_size","$disk_home_used");

EOF

}

insert_time=`date +%Y%m%d-%H%M%S-%N`

server_ip="`/sbin/ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}' | tail -1`"

cpu_used=`vmstat 5 1 | awk 'NR>2 {print 100-$15}'`

if [ ${cpu_used} -gt ${maxcpu} ];then

echo "warning!!! `date +%Y%m%d-%H%M%S` $server_ip cpu used $cpu_used% over 80% " | mail -s "`date +%Y%m%d-%H%M%S` $server_ip cpu uesd over 80%" $notice_mail

fi

cpu_model=`cat /proc/cpuinfo | grep "model name" |awk '{print $NF}'|sed -n '1p'`

cpu_num=`cat /proc/cpuinfo | grep "model name" |wc -l`

mem_size=`free -m | sed -n '2p' | awk '{printf "%.02f\n",$2/1024}'`

mem_used=`free -m |awk 'NR>2&&NR<=3 {printf "%.0lf",$3/($3+$4)*100}'`

if [ ${mem_used} -gt ${maxmem} ];then

echo "warning!!! `date +%Y%m%d-%H%M%S` $server_ip mem used $mem_used% over 80% " | mail -s "`date +%Y%m%d-%H%M%S` $server_ip mem uesd over 80%" $notice_mail

fi

#disk_default_size=`df -h | awk 'NR>1&&/%/ && $6!="/dev/shm" && $6!="/boot" {print $1}' |sed -n 1p`

disk_default_size=`df -h | awk '"/"==$NF{print $(NF-4) }'`

disk_default_used=`df -h | awk '"/"==$NF{print $(NF-1) }'`

disk_home_size=`df -h | awk 'NR>1&&/%/ && $6!="/dev/shm" && $6!="/boot" {print $1,$(NF-1),$NF}' | grep "/home" | awk '{print $1}'`

disk_home_used=`df -h | awk 'NR>1&&/%/ && $6!="/dev/shm" && $6!="/boot" {print $1,$(NF-1),$NF}' | grep "/home" | awk '{print $(NF-1)}'`

insert_log;

diskusedp=`df -h | grep % | awk 'NR!=1 {print $(NF-1)}'`

echo "$diskusedp"

for p in ${diskusedp}; do

pn=`echo "$p" | sed 's/\%//g'`

# echo $pn

if [ ${pn} -gt ${maxdisk} ];then

echo "warning!!! `date +%Y%m%d-%H%M%S` $server_ip `df -h | grep -w "$p"` over 80% "

echo "warning!!! `date +%Y%m%d-%H%M%S` $server_ip `df -h | grep -w "$p"` over 80% " | mail -s "`date +%Y%m%d-%H%M%S` $server_ip uesd over 80%" $notice_mail

else

echo "`date +%Y%m%d-%H%M%S` `df -h | grep -w "$p"` lower 80% "

fi

done

更多技术交流,加入qq群115980409!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: