以下是本人自己民写的一个Shell脚本,可以监控使用的VPS的CPU、Load、Memory、网络传输、网站能否打开等情况,感觉挺有用的,现在分享出来给需要的朋友.
几个月前开始使用VPS,每月限制300GB流量,流量方便基本够用了,但是有时候由于受到一些恶意访问,导致CPU、Memory等资源消耗较大,导致VPS上的博客网站响应时间太慢甚至有时根本无法打开网页,所以,我简单做了个脚本来进行监控和发邮件报警.
由于不是做很专业的运维,暂时不想上很专业的监控工具,如:Nagios、Puppet、Cacti、Zabbix等,所以自己手动了个Shell脚本来监控我关心的CPU、Load、Memory、网络传输、博客网站能否打开等内容,将该监控脚本分享如下:
https://github.com/smilejay/shell/blob/master/sh2013/vps_monitor.sh,代码如下:
- #!/bin/bash
- #set-x
- #thescripttomonitormyVPS
- #Itwillalertwhenmemory,load,CPU%,networking,httpd/mysqldorhome-page
- #isinanabnormalstate.
- #author:Jay
- #date:2013-10-16
- EMAIL="smile665@gmail.com"
- WARN_MSG=""
- #alertwhenfreememoryislessthan50MB
- functionmem_free()
- {
- threshold=50#50MBfreememory
- free_mem=$(free-m|grep"buffers/cache"|awk'{print$4}')
- if[$free_mem-lt$threshold];then
- WARN_MSG=$WARN_MSG"Freememeoryislessthan$thresholdMB.n"
- return1
- fi
- return0
- }
- #alertwhenload(5min)islargerthan4
- functionload_avg()
- {
- threshold=4#loadis4
- load_5min=$(cat/proc/loadavg|awk'{print$2}')
- if[$(echo"$load_5min>$threshold"|bc)-eq1];then
- WARN_MSG=$WARN_MSG"5minaverageloadislargerthan$threshold.n"
- return1
- fi
- return0
- }
- #alertwhenCPUidle%islessthan20%
- functioncpu_idle()
- {
- threshold=20#CPUidle%20%
- cpu_idle=$(sar15|grep-i'Average'|awk'{print$NF}')
- if[$(echo"$cpu_idle<$threshold"|bc)-eq1];then
- #inprintfcmd,%%representsasingle%
- WARN_MSG=$WARN_MSG"CPUidle%%islessthan$threshold%%.n"
- return1
- fi
- return0
- }
- #alertwhennetworkingtxspeedislargerthan80kB/s
- functionnetwork_tx()
- {
- threshold=80#TXspeed80kB/s
- interface=eth0
- tx_speed=$(sar-nDEV105|grep"Average"|grep"$interface"|awk'{print$6}')
- if[$(echo"$tx_speed>$threshold"|bc)-eq1];then
- WARN_MSG=$WARN_MSG"networkingTXspeedislargerthan$thresholdkB/s.n"
- return1
- fi
- return0
- }
- #alertwhenhttpdormysqldprocessdoesn'texist
- functionhttpd_mysqld()
- {
- ps-ef|grep'httpd'|grep-v'grep'
- if[$?-ne0];then
- WARN_MSG=$WARN_MSG"httpdprocessdoesn'texist.n"
- return1
- else
- ps-ef|grep'mysqld'|grep-v'grep'
- if[$?-ne0];then
- WARN_MSG=$WARN_MSG"mysqldprocessdoesn'texist.n"
- return1
- fi
- fi
- return0
- }
- #alertwhen'Stayhungry'doesn'texistinthehomepagehttp://smilejay.com/
- functionhome_page()
- {
- url=http://smilejay.com/
- keywords="Stayhungry"
- curl-sL$url|grep-i"$keywords"
- if[$?-ne0];then
- WARN_MSG=$WARN_MSG"keywords'$keywords'doesn'texistonlink$url.n"--phpfensi.com
- return1
- fi
- return0
- }
- #useanarraytostorethereturnvalueofeachmonitoringfunction
- mem_free
- chk[1]=$?
- load_avg
- chk[2]=$?
- cpu_idle
- chk[3]=$?
- network_tx
- chk[4]=$?
- httpd_mysqld
- chk[5]=$?
- home_page
- chk[6]=$?
- #sendwarningemailtothewebmasterifanyofthecheckfails.
- foriin$(seq16)
- do
- if[${chk[i]}-ne0];then
- printf"$WARN_MSG"|mailx-s"Warningfromsmilejay.com"$EMAIL
- exit1
- fi
- done