website_aliveness.pl

Code Index:



NAME

website_aliveness.pl <website> <frequency>


DESCRIPTION

Test for a <website> aliveness every <frequency> seconds.

Usually write to website_aliveness.pl.log file.


COPYRIGHT

Copyright 2010 Etienne LEMEE <coding AT etilem DOT net>

This piece of code is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


#!/usr/bin/perl -w

use strict;
use Socket;
use LWP::Simple;
use POSIX qw(strftime);

@ARGV > 1 or die << "USAGE";

usage: $0 <hostname> <frequency>

test for a website aliveness every <frequency> seconds
USAGE

sub is_alive {
        my $host = shift;
        return head("http://" . $host) ? "OK" : "KO";
}

sub write_log_and_print {
        my ($file, @msg) = @_;
        open my $OUT, '>>', $file or die $!;
        print $OUT @msg;
        close $OUT;
        print @msg;
}

sub now {
        return strftime("%Y-%m-%d %H:%M:%S", localtime);
}

sub get_ip {
        my $host = shift;
        return inet_ntoa(inet_aton($host));
}

my ($host, $freq) = @ARGV;

my $file = $0 . ".log";
open my $OUT, '>', $file or die $!;

my $addr = get_ip($host);

while(sleep $freq) {
    write_log_and_print $file,
    now(), " : ", $host, " : ", $addr, " : ", is_alive($host), "\n";
}