Friday, February 26, 2010

Perl Script to assess stability of a home ISP service

#!/usr/bin/perl

## app to log the availability of WAN items

$SIG{INT} = \&tsktsk;

use Getopt::Std;
use vars qw/ $opt_f $opt_q /; ### runForever, runQuiet,
getopts("qf") die "Please check options";

my $bell = "\a";
my $MaxRecs = 90;

print "Ctrl-C to dump last $MaxRecs records\n";
print "Options: forever:$opt_f quiet:$opt_q\n";
if ($opt_q)
{
$bell = "";
}

use Net::Ping;

my $p = Net::Ping->new("icmp", 2, 128);
## my $q = Net::Ping->new("syn", 2, 128); ## ?

my $router = '192.168.1.1';
my $isp = "82.39.210.1"; ## Virgin Gateway : Katie's was "82.39.226.1"
my $dns = '194.168.4.100';
my $bbc = '212.58.244.141'; ## 'www.bbc.co.uk';
my $google = "www.google.co.uk"; ## www-tmmdi.l.google.com [66.102.9.99]

my $count = 0;

my @hosts = ($router, $isp, $dns, $bbc, $google);
my @history = qw( FIRST );

open(my $fileH, '>>', "pingTests.txt") or die $!;

use IO::Handle;
$fileH->autoflush(1);
STDOUT->autoflush(1);

($s, $m, $h, $d) = localtime() ;
$line = sprintf "%02d %02d:%02d:%02d RTR ISP DNS BBC GGL\n", $d, $h, $m, $s;

print $fileH "\n\nRESTART\n\n".$line;
print $line;

while (1)
{
local $line;
local $failed;

($s, $m, $h, $d) = localtime() ;
$line = sprintf "%02d %02d:%02d:%02d ", $d, $h, $m, $s;
$failed = 0;
foreach (@hosts)
{
$ok = $p->ping($_); ## ($ok,$rtt,$ip) = ..
if ($ok)
{
##print "$_: $ok [$ip] ACKed in $rtt seconds.\n";
$line .= "Ok ";
}
else
{
##print "$_: $ok [$ip] FAILED.\n";
$line .= "Fail ";
$failed = 1;
}
}

if ($failed)
{
print "\n".$line."\n".$bell;
}
print $fileH $line."\n";

push (@history, $line);
if ($count>$MaxRecs) ## keep a history of most recent reports
{
shift (@history);
}

printf "%04d %02d:%02d:%02d ...\r", $count, $h, $m, $s;

sleep(2);
$count ++ ;
}



sub tsktsk {
$SIG{INT} = \&tsktsk; # Signal Handler''
my $index = 1;


warn "Ctrl-C\n";
## print @hosts;

($s, $m, $h, $d) = localtime() ;
$line = sprintf "%02d %02d:%02d:%02d RTR ISP DNS BBC\n", $d, $h, $m, $s;
print $line;

foreach (@history)
{
printf "%03d %s\n", $index++, $_;
}

if ( ! $opt_f) ## == ! $runForever
{
$p->close();
exit (0) ;
}
}