Skip to content

Instantly share code, notes, and snippets.

@aspyct
Created June 25, 2012 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aspyct/2988999 to your computer and use it in GitHub Desktop.
Save aspyct/2988999 to your computer and use it in GitHub Desktop.
Perl & Bash scripts to warn you if your website is failing
#!/bin/bash
# Actual recipient and sender are defined in another file
script_dir=`dirname $0`;
script_name=`basename $0`;
config_file="$script_dir/config-$script_name";
if [ -f $config_file ]; then
source $config_file;
else
# Vars for testing purpose
SENDMAIL=/usr/sbin/sendmail
URL=www.example.com
EXPECTED=403 # Be sure to test this ;)
RECIPIENT=a.dotreppe@aspyct.org; # Set this to your email address
SENDER=debug@aspyct.org;
fi;
test_url.pl $URL $EXPECTED --quiet
status_code=$?
if [ $? ]; then
echo "Server not responding as expected" >&2
echo "Sending alert mail to $RECIPIENT from $SENDER";
tmpfile=`mktemp`;
echo "From: $SENDER" >> $tmpfile;
echo "To: $RECIPIENT" >> $tmpfile;
echo "Subject: $URL down" >> $tmpfile;
echo "" >> $tmpfile;
echo "The server check returned $status_code" >> $tmpfile;
echo "We were expecting $EXPECTED" >> $tmpfile;
$SENDMAIL -t < $tmpfile;
rm $tmpfile;
fi;
#!/usr/bin/env perl
use strict;
use Switch;
use Getopt::Long;
# Parameters
my $expected = 200;
my $url;
my $quiet = 0;
my $result = GetOptions("quiet" => \$quiet);
if ($quiet) {
open STDERR,'>/dev/null';
}
my $argcount = @ARGV;
switch ($argcount) {
case 2 {
$expected = $ARGV[1];
next
}
case [1..2] {
$url = $ARGV[0];
}
}
if (!defined $url || $url eq "help") {
print "Usage: $0 <url to test> [<expected return code> [--quiet]]\n";
if ($url == undef) {
exit 1;
}
}
my @headers = `curl -sIL $ARGV[0]`;
if (@headers == 0) {
print STDERR "No return headers\n";
exit 2;
}
my $status = $headers[0];
if ($status =~ /^http\/\d\.\d +(\d+)/i) {
my $code = $1;
if ($code ne $expected) {
print STDERR "Got $code, expected $expected\n";
if ($code) {
exit $code;
}
else {
exit 3;
}
}
}
@aspyct
Copy link
Author

aspyct commented Jun 25, 2012

Copy this gist to your perl-enabled server and run it with a cron job :) You should maybe even wrap it in another script to send you a mail/text message if the check fails.

Usage:
Want a 200 ? ./test_url.pl www.aspyct.org
Want a 403 ? ./test_url.pl www.aspyct.org 403
No error message ? ./test_url.pl --quiet ...

@aspyct
Copy link
Author

aspyct commented Aug 19, 2019

Or, for a more elaborate solution, you could also look into Prometheus (https://prometheus.io) and its Blackbox Exporter (https://github.com/prometheus/blackbox_exporter)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment