当前位置: > shell编程 >

shell脚本监控服务器宕机、检测、报警程序

时间:2014-08-09 17:58来源:linux.it.net.cn 作者:it
宕机监控报警程序


  • 需求来源
宕机对运维人员来说,最痛苦了。如何检测一台服务器是否还在正常运行,如果该服务器宕机,如何在第一时间监测到并通知一线运维人员进行维护,最大化减少损失。
 
  • 程序功能
对指定服务器进行宕机监测,如果确实宕机,则发送email到139邮箱(绑定手机,实现短信报警)
脚本如下:
 
 
#!/bin/bash  
#author         longxibendi  
#blog           http://blog.csdn.net/longxibendi  
#function       ping  a  host   and   output  to  file     ping_longxibendi.log  
#ping  destination  
function_ping ()  
{  
 ping  -c 3     172.29.141.115  >  ping_longxibendi.log  
}  
#downtime detection and  send email to   SA  
function_downtime_detection_AND_sendemail ()  
{  
         if  [ "`cat ping_longxibendi.log | grep Unreachable`"  !=  ""    ] ; then  
                /usr/local/bin/sendEmail -f monitor_sys@163.com -t longxibendi@139.com -s smtp.163.com -u "Server downtime" -xu monitor_sys -xp 123456789 -m "`date;echo "172.29.141.115" ` "  
         fi  
}  
#main function  
function_main ()  
{  
while    true  
do  
        function_ping ;  
        sleep   2  
        function_downtime_detection_AND_sendemail ;  
        sleep  2  
  
done  
}  
function_main ;  
 
 
  •  
1.通过  function_ping    ,每隔4秒对 主机 172.29.141.115 进行ping 操作,(当然,如果主机172.29.141.115的防火墙,或者内过滤ICMP包,那么这个程序显然不能用)将输出重定向到ping_longxibendi.log 文件中
 
2.通过 function_downtime_detection_AND_sendemail  ,每隔4秒,通过ping_longxibendi.log判断是否有没有ping通的迹象,如果有,则调用 sendEmail 邮件(手机短信)报警。
 
3.监控间隔时间说明  ,可以将 第一个 sleep 改为   150   ,第二个 sleep 改为  150  ,这样每隔5分钟监控一次。
 
四.使用环境说明
 
1.主机 A(172.29.141.112)   主机B (172.29.141.115)    ,
   在A上部署该监控程序(monitor_down.sh),用于监控B
 
2.正常情况下A能ping通B
   因为用的ping命令,所以如果使用该程序,需要在正常情况下A ping 通 B  。对企业来说,这可能就需要防火墙和Linux内核参数(当然,如果之前没有修改net.ipv4.icmp_echo_ignore_all,则不需要调整)
 
3.安装了 sendEmail  并 在139邮箱注册(绑定手机),方可有邮件(短信)报警提示
 
五.程序测试
 

[root@localhost monitor]# sh  monitor_down.sh
May 21 20:33:46 localhost sendEmail[9175]: Email was sent successfully!
May 21 20:33:56 localhost sendEmail[9204]: Email was sent successfully!
Terminated
[root@localhost monitor]# 
 
六.程序扩展
这个程序,只是实现宕机监控并报警,但没有实现故障转移,自动切换功能。其实,只要稍微修改一下程序就可以实现故障转移,自动切换。故障转移,比如可以通过在热备机A上部署该程序,监控B,一旦B宕机,则A执行浮动改IP和更新下层服务器arp列表即可。可以参考
http://blog.csdn.net/longxibendi/archive/2011/05/21/6436606.aspx
(责任编辑:IT)
------分隔线----------------------------
栏目列表
推荐内容