Friday, November 7, 2014

To check http or https webpage availability using www::Mechanize perl module

#!/usr/bin/perl
#use strict;
#use warnings;
use WWW::Mechanize;
use HTTP::Cookies;
use Time::HiRes;
use Getopt::Long;
my ($expect,$url);
GetOptions(
        'url1=s'                 => \$url1,
        'expect=s'              => \$expect,
        'debug=s'               => \$debug) or HELP_MESSAGE();

my $mech = WWW::Mechanize->new(autocheck => 0);
$mech->cookie_jar(HTTP::Cookies->new());
my $start1 = Time::HiRes::time();
$mech->get ($url1);
my $responsecode1 = $mech->status();
if (defined $debug)
{
print $mech->content( raw => 1 );
}
my $time1 = sprintf("%.2f",Time::HiRes::time()-$start1);
 if( $responsecode1 != 200 )
        {
#       my $time1 = sprintf("%.2f",Time::HiRes::time()-$start1);
        print "Unable to get the URL, check the URL, response code:$responsecode1". "|time=" . $time1 . "s;60" . "\n";
        exit(2);
        }
else
{
        $match= $mech->content( raw => 1 );
        if ($match =~ m/$expect/)
         {
        print "response code:$responsecode1". "|time=" . $time1 . "s;60" . "\n";
        exit(0);
         }
        else
        {
        print "Content Match error, possible redirection, response code:$responsecode1". "|time=" . $time1 . "s;60" . "\n";
        exit(2);
        }
}
sub HELP_MESSAGE {
        print "$0 -u <url> -e <expect> -d \"debug\"\n";
        print "\t -u <url> # url string to run basic auth against do not prefix with http or https\n";
        print "\t -e <expect> # string to query on the page\n";
        print "\t -d \"debug\"# debugging mode print page content\n";
        print "\t e.g $0 -u \"https\:\/\/foobar.com\/foo\" -e \"Hello\"\n";
        print "\t Please follow the syntax as mentioned above in sequence don't change the parameter position \n";
        exit 0;
}