Website Monitoring & send Email when down

We use a perl script to monitor our webservers, and if any are down, send an email (SMS) to the right people.

With thanks and compliments to these guys
Here is the perl script, monitor-website.pl

#!/usr/bin/perl

use Getopt::Std;

# Define the address the alerts should come from

$monitor_email = "Website_Monitor";

# Define global variables
$curl_executable = "/usr/bin/curl";
$mail_executable = "/usr/sbin/sendmail";
$OPT_STRING = 'hs:e:';

# Start program
&main();

sub main {

# Read in the options
getopts( "$OPT_STRING", \%opt ) or usage();

# Set variables
my $url_header = "";
my $url_body = "";
my $email_address = "";
my $url = $ARGV[0];
my $valid_string = "";

# Determine options
if ($opt{s}) { $valid_string = $opt{s};}
usage() if $opt{h};
usage() if !$opt{e};

# Define more variables
$email_address = $opt{e};

# Monitor URL
$url_header = `$curl_executable -I -s $url`;

if ($url_header =~ /200 OK/){
$url_body = `$curl_executable -s $url`;
if ($url_body =~ /$valid_string/){
#print ("$url_header\n");
}
else{
&send_warning($email_address, $url);
}
}
else{
&send_warning($email_address, $url);
}

}

sub send_warning {

my ($email_address,$url) = @_;

# Create timestamp
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
$year = $year + 1900;
$mon = $mon + 1;
my $time_stamp = $year."-".$mon."-".$mday." ".$hour.":".$min.":".$sec;

my $email_content = $url ." failure at ". $time_stamp . "\n";

unless(open (MAIL, "| /usr/sbin/sendmail -t")) {
print "error.\n";
warn "Error starting sendmail: $!";
}
else{
print MAIL "From: " . $monitor_email . "\n";
print MAIL "To: " . $email_address . "\n";
print MAIL "Subject: Website URL Monitor Failure\n\n";
print MAIL $email_content;
close(MAIL) || warn "Error closing mail: $!";
print ("$email_content");
}
}

sub usage {

print STDERR << "EOF"; This program monitors HTTP URLS usage: $0 [-h] [-s "string"] -h : This (help) message -e email-address : The email address that should be alerted. -s : Unique string found on the web page that proves it is working correctly example: $0 -s -e email-address URL EOF exit; }

Now with that file in place, I create a shell to batch this, called monitor.sh

monitor-website.pl -e my@email.address http://www.omniweb.com
monitor-website.pl -e my@email.address http://newserver.omniweb.com

chmod +x both of these and put the monitor.sh in cron to run every 10 minutes (ideally on a remote server, since if your whole server is down this won't run!) and voila, notification when your sites are down.

## Monitor websites every 10 minutes, email when outages
*/10 * * * * root monitor_sites.sh > /var/log/monitor.log

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

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