Free Web Server Monitor

Following up on my previous article on server monitoring software I decided to whip up a quick monitoring script, just for fun. This script is a standalone monitor for HTTP (ie. web) and checks for the existence of a keyword or phrase and also it checks if the server is responding. It can monitor multiple sites/pages and if there is a problem it will send an email alert.

While fairly basic it is in fact quite functional and can easily be expanded upon. For example you could easily include SMS alerts, or additional monitor types. A useful addition to reduce false positives would be to recheck a page after a certain delay, before sending an alert.

The script is written in Perl and has very minimal requirements – just LWP::UserAgent which you may already have but if not you can get from cpan (cpan -i LWP::UserAgent) or install with Yum or whatever package management system you use.

[code]#!/usr/bin/perl
#
# Simple http monitor which checks for existence of keyword
# Free to use and modify but a link back to sysops.ie would be appreciated (but optional)
#
use LWP::UserAgent;

my $NotifyAddress = “you\@gmail.com,you2\@hotmail.com”;
my $AlertFrom = “alert\@yourdomain.com”;
my $Timeout = 90; # seconds
my $Sendmail = “/usr/sbin/sendmail”;

# add your sites/pages and keywords here..
my %Sites = (
“http://google.com/” => “search”,
“http://bing.com/” => “Feedback”,
);

while (($Key, $Value) = each(%Sites)) { PageFetch($Key,$Value); }

sub PageFetch
{
my ($URL,$Keyword) = @_;
my $Error=0;

my $Browser = LWP::UserAgent->new();
$Browser->default_header(‘Content-Encoding’ => “UTF-8”);
$Browser->timeout($Timeout);
my $Response = $Browser->get(“$URL”);

if ($Response->is_success)
{
my $Page = $Response->decoded_content;
if ($Page !~ /$Keyword/gi) { $Error=1; print “$URL NOT ok\n”;} else { print “$URL ok\n”; }
# print “$Page\n\n\n”;
} else { $Error=2; }

if ($Error>=1)
{
my %ErrorMessage = (‘1’ => “$URL failed – $Keyword not found!”,”2″ => “$URL failed – Server down!”);
Email($NotifyAddress,$AlertFrom,”ALERT for $URL”,$ErrorMessage{$Error},”text/plain”);
#print “fetch failed for $URL – $ErrorMessage{$Error}\n”;
}
return;
}

sub Email
{

my($To,$From,$Subject,$Body,$Type) = @_;
open (MAIL, “| $Sendmail -t”);
print MAIL “From: $From\n”;
print MAIL “To: $To\n”;
print MAIL “Subject: $Subject\n”;
print MAIL “Content-type: $Type\n\n”;
print MAIL “$Body\n”;
close MAIL;

}
[/code]

 

Place it anywhere on your server and run from cron every 5 minutes or whatever you want, like so..

*/5 * * * * perl /path/to/thiscript.pl

If you find this useful please link to this blog although you don’t have to, the script is still free to use or ignore or do whatever you want with.

*Disclaimer* don’t blame me if something doesn’t work quite right – I make no guarantees so test it yourself!

Suggestions for improvement welcome. I’ll probably make similar scripts for other monitor types soon as well.

You may also like...