傻小烨 2011-03-21
最近服务器经常宕机,导致网站无法正常运行,于是写了一个自动检测网站服务器alive状态的脚本,从网上查到了perl和shell两种脚本的实现方式,同时加入了邮件通知的脚本。
Perl采用的是ICMP检测主机,Perl的脚本如下:
#!/usr/bin/perl -w use Net::Ping; use Net::SMTP; use MIME::Base64; my @host_array=('192.168.0.10','192.168.0.11'); my $p = Net::Ping->new("icmp"); foreach $host (@host_array) { # print "$host is "; unless($p->ping($host,2)) { &sendmail($host." is down",$host." is down"); } # print "\n"; # print "NOT " unless $p->ping($host, 2); # print "reachable.\n"; sleep(1); } sub sendmail(){ my $mailhost = "smtp server domain"; # the smtp host my $mailfrom = 'your email address'; # your email address my $mailto='email address you want to send'; my $subject=$_[0]; my $text = $_[1]; $smtp = Net::SMTP->new($mailhost, Hello => 'localhost', Timeout =>120, Debug => 1); $smtp->auth('user name','password'); $smtp->mail($mailfrom); $smtp->to($mailto); $smtp->data(); $smtp->datasend("Content-Type:text/html;charset=utf-8\n"); $smtp->datasend("Content-Transfer-Encoding:base64\n"); $smtp->datasend("To:=?utf-8?B?".encode_base64($mailto,'')."?= <$mailto> \n"); $smtp->datasend("From:=?utf-8?B?".encode_base64($mailfrom,'')."?= <$mailfrom> \n"); $smtp->datasend("Subject:=?utf-8?B?".encode_base64($subject,'')."?=\n\n"); $smtp->datasend("\n"); $smtp->datasend(encode_base64($text,'')." \n"); $smtp->dataend(); } $p->close();
Shell的脚本通过ping检测主机状态,贴一下网友的代码吧
#!/bin/sh pingcmd() { prefix="SERVER $1 PING $2" ping -w 1 -c 1 $2>/dev/null ret=$? if [ $ret -eq 0 ] then printf "$prefix\t OK\n" else printf "$prefix\t ERROR\n" fi return 0 } echo "---------------------------------------" echo "核心网1 1.1 PING FROM 1" echo "---------------------------------------" server0="182.87.1.3" server1="182.87.1.2" pingcmd $server0 $server1 echo ""
可以通过加入相应的通知类库,如飞信的开源接口,做到即时报警通知。
参考资料:
http://blogold.chinaunix.net/u/25264/showart_1360067.html
http://bbsea123.blog.163.com/blog/static/722651472010126111454814/