A bit more Perl and eval – this time with WWW::Mechanize

So while all of the patriotic Brits were flag waving for the Queens Diamond Jubilee, I was asked to write a Nagios test to monitor whether our email archiving system was working. The test specified that if a user could log into the portal without error, all was well with the world. Now this system runs on Windows so is out of my administrative control and I’m not in a position to get access to logs, system resources, etc, so I decided the best solution was to use WWW::Mechanize. I’m pretty new to WWW::Mechanize, so after the buttock clenching over the spelling was dealt with, a quick trip to CPAN spilled the details pretty quickly. To start with I just tested the mechanism with this:

#! /usr/bin/perl -w

use strict;
use WWW::Mechanize;

my $mech = WWW::Mechanize->new();
my $url = 'http://www.gconnect.net';
my $username = shift;
my $password = shift;

$mech->get( $url );
my $status = $mech->status();
print "Status is: $status\n"; 

and the output is:

# ./test.pl
Status is: 200

As this is a Nagios test i want it to exit with a value of 2 and give me a sensible message if the process fails. To test what happens, I’ll just add at ‘t’ to the end of the url which should break it and make the process fail. Now when I run it again:

# ./test.pl
Error GETing http://www.gconnect.nett: Can't connect to www.gconnect.nett:80 (Bad hostname 'www.gconnect.nett') at ./test.pl line 11

In order to trap that error nicely, and allow the program to exit with the criteria I mentioned above, we need to use ‘eval’…

#! /usr/bin/perl -w

use strict;
use WWW::Mechanize;

my $mech = WWW::Mechanize->new();
my $url = 'http://www.gconnect.net';
my $username = shift;       
my $password = shift;       
                            
eval{$mech->get( $url );};  
                            
if ($@){                    
        print "CRITICAL: Unable to connect to server\n";
        exit 2;             
}                           
                            
my $status = $mech->status();
print "Status is: $status\n";

With the correct URL, we get the response of 200, with the broken URL we get:

# ./test.pl
CRITICAL: Unable to connect to server

It does not get much more Nagios friendly than that!

This entry was posted in Perl and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *