uttsu.com > Perl >

Webサーバー監視スクリプト

httpサーバーが動いているか監視し、ダウンしていたらメールで知らせてくれるスクリプトです。cronで定期的に実行します。

使い方

is_alive_http.pl 目的のサーバー

例:is_alive_http.pl uttsu.com

is_alive_http.pl

#!/usr/local/bin/perl

# is_alive_http.pl - httpサーバーが動いているか監視
# (C) Takashi Utsunomiya
# http://uttsu.com/
# Usage: is_alive_http.pl server

# 2003.02.09    ver 1.01
# - proxy使わず直接接続に。
# 2003.02.02    ver 1.00
# - 作成開始, 完成

use strict;

my $host = $ARGV[0] or die;
my $mail = 'メールアドレス';

main();

# ◆
sub main {
    if (!is_alive_http($host)) {
        print "$host is down\n";
        system("echo '$host is down' | mail $mail");
    }
}

# ◆
sub is_alive_http {
    my $target = shift;
    my @result;

    my $addr = (gethostbyname($target))[4];
    my $name = pack("S n a4 x8", 2, 80, $addr);
    socket(SOCKET, 2, 1, 0);
    connect(SOCKET, $name) or return 0;
    binmode(SOCKET);
    select(SOCKET); $| = 1; select(STDOUT);
    print SOCKET "OPTIONS * HTTP/1.0\n\n";
    @result = <SOCKET>;
    close(SOCKET);

    return (join('', @result) =~ /200 OK/ ? 1 : 0);
}


Copyright (C) Takashi Utsunomiya. All Rights Reserved.
2003.04.04掲載