2011年1月

perl监控tcp端口加邮件通知

#!/usr/bin/perl

use IO::Socket;
use Net::SMTP_auth;
use strict;



# mail
use constant MAIL_PORTS => ('25','110');
use constant MAIL_SERVERS => ('10.10.10.10');



my $mailhost = 'smtp.163.com';
my $mailfrom = 'test@163.com';
my @mailto = 'xxxxxxx@139.com';
my $subject = '';

my $user = 'test';
my $passwd = 'test';





##############################
# Server port is alive check
##############################
sub check_server_alive {
my ( $server, $port ) = @_;
my $sock = IO::Socket::INET->new(
PeerAddr => $server,
PeerPort => $port,
Proto => 'tcp',
Timeout => 6
);
if ( !$sock ) {
return 0;
}
$sock->close();
return 1;
}

##############################
# Send notice mail
##############################
sub SendMail() {

my $smtp = Net::SMTP_auth->new( $mailhost, Timeout => 120, Debug => 1 )
or die "Error.\n";
$smtp->auth( 'LOGIN', $user, $passwd );

foreach my $mailto (@mailto) {
$smtp->mail($mailfrom);
$smtp->to($mailto);
$smtp->data();
$smtp->datasend("To: $mailto\n");
$smtp->datasend("From:$mailfrom\n");
$smtp->datasend("Subject: $subject\n");
$smtp->datasend("\n");
$smtp->dataend();
}

$smtp->quit;
}


##############################
# Check server alive main
##############################
sub monitor_main {


# check mail
foreach my $s_tem (MAIL_SERVERS) {
foreach my $p_tem (MAIL_PORTS) {

if ( !&check_server_alive( $s_tem, $p_tem ) ) {


print "$s_tem mail server $p_tem port is fail!" . "\n";
$subject = "$s_tem mail server $p_tem port is fail";
&SendMail();
}
}
}


}





##############################
# Main running
##############################

&monitor_main();