Code:
#!/usr/bin/perl
use Getopt::Std;
# Define the address the alerts should come from
$monitor_email = "[email protected]";
# 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 = "</html>";
# 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;
Bookmarks