当先锋百科网

首页 1 2 3 4 5 6 7

一个自动检测网站服务器alive状态的脚本,分别由perl和shell两种脚本来实现,且可以邮件通知监测到的异常。

例1,Perl采用ICMP检测主机状态。

Perl代码

复制代码 代码示例:

#!/usr/bin/perl -w

#edit: www.jquerycn.cn

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,'')."?= \n");

$smtp->datasend("From:=?utf-8?B?".encode_base64($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();

例2,Shell通过ping检测主机状态

Shell代码

复制代码 代码示例:

#!/bin/sh

#edit: www.jquerycn.cn

#

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 ""

以上分享了二个监测Linux服务器状态的脚本,希望大家能够在实际的生产环境中有效利用,对大家有一定的帮助。