<?php

一个简单的由perl实现的端口监控脚本,邮件通知+手机短信通知

先说一下原理,1,根据端口的响应时间来判断是否宕掉;2,如果宕掉了就发一封邮件到指定邮箱(注意:需要用到sendmail, 要安装配置好)
另一个,如果需要手机短信通知。其实不需要搞什么飞信接口了,直接去注册一个139邮箱,免费的邮件到达短信通知,包括邮件内容的! 如果不想用139邮箱,也可以选择qq邮箱的短信通知服务。或其他服务商,任你选择了。

#!/usr/bin/perl -X

use IO::Socket;

##############################
# Constant define (configure)
##############################
# mail config
use constant MAIL_ADDR          => ('to'=>'zhys9@139.com', 'from'=>'nginx.org@gmail.com');
# common config
use constant MD5SUM_FILE        => '/tmp/__monitor_md5sum_hash';
# apache
use constant WEBSERVER_PORT        => 80;
use constant WEBSERVER_HOSTS     => ('localhost');
# mysql
use constant MYSQL_PORT         => 3306;
use constant MYSQL_HOSTS      => ('localhost');
# memcache
use constant PHPFCGI_PORT      => 9000;
use constant PHPFCGI_HOSTS   => ('localhost');

##############################
# Server port is alive check
##############################
sub check_server_alive {
    my($server, $port) = @_;

    $sock = IO::Socket::INET->new(PeerAddr=>$server, PeerPort=>$port, Proto=>'tcp', Timeout=>1);
    if (!$sock){
        return 0;
    }
    $sock->close();
    return 1;
}

##############################
# Send notice mail
##############################
sub send_mail {
    my ($subject, $content) = @_;;
    my %mailaddr = MAIL_ADDR;

    open(MAIL, "|/usr/sbin/sendmail -t");

    ## Mail Header
    print MAIL "To: $mailaddr{'to'}\n";
    print MAIL "From: $mailaddr{'from'}\n";
    print MAIL "Subject: $subject\n\n";

    ## Mail Body
    print MAIL "$content\n";

    close(MAIL);

}

##############################
# Check server alive main
##############################
sub monitor_main {
    # check apache
    foreach $item (WEBSERVER_HOSTS) {
        if (!check_server_alive($item, WEBSERVER_PORT)) {
            send_mail("$item web server is down", "$item web server is down. please timely restoration");
        }
    }
    # check mysql
    foreach $item (MYSQL_HOSTS) {
        if (!check_server_alive($item, MYSQL_PORT)) {
        print("mysql is down.");
            send_mail("$item mysql server is down", "$item mysql server is down. please timely restoration");
        }
    }
    # check fast-cgi
    foreach $item (PHPFCGI_HOSTS) {
        if (!check_server_alive($item, PHPFCGI_PORT)) {
            send_mail("$item fast-cgi is down", "$item fast-cgi is down. please timely restoration");
        }
    }
}

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

monitor_main();

本脚本参考文档:
http://blog.csdn.net/re_think/archive/2009/06/25/4296833.aspx
perl发送邮件:http://www.cyberciti.biz/faq/sending-mail-with-perl-mail-script/

Tags: , , ,

Leave a Reply