Web Server Up Script

I hade some problems with this web server when I was on a business trip i Japan. It was very frustrating not being able to restart the web server remotely which would have made the trick (in this case).

To handle this I have made the following improvements.

  1. Allow access to my servers from anywhere in the world through a trusted relay. I only permit SSH access from a set of "semi-trusted" ISP's and not everyone in the world. I have complemented this setup with a single trusted relay which is allowed to access my servers. This way I am able to access my servers from everywhere in the world by passing through this relay.

  2. I have created a script to test if the web server is running. If the web server isn't running I will be informed via email within an hour. Later I may also allow the web server to be restarted automatically when this happen.

The web server test script can be found below.


# Simple script to determine if web server is up or not
# Dependencies: curl and mail setup correctly
# Typically run from cron script

# Get the page ($1) with cURL and return the response code
get_http_page() {
    resp=`/usr/local/bin/curl -m 1 -sSfI $1 2> /dev/null | /usr/bin/grep "HTTP/1.1"`
    if [[ $err -ne 0 ]]
        return $err
    tmp=${resp#*1.1 }
    code=${tmp%% *}
    echo "$code"

if [ -z "$1" ]
    echo "Usage: ./webserver_check <URL>"
    echo "       ./webserver_check" 
    exit 1

# Try to access specified page 5 times, break if successful otherwise count failed attempts
for i in 1 2 3 4 5
    code=`get_http_page $1`
    if [[ $? -eq 0 ]]
    sleep 2

# Notify user if all attempts failed
if [[ $failed -eq 5 ]]
    msg="Webserver on URL: $1 is down, 5 of 5 failed"
    logger "$msg"
    echo $msg | /usr/bin/mail -s 'Webserver is down!' webserver.admin@gmail.com
    echo $msg | /usr/bin/mail -s 'Webserver is down!' root
    msg="Webserver on URL: $1 is running $failed of 5 failed"
    logger "$msg"

I run the script hourly from cron on a different machine on the same network.

# check webserver up
10      *       *       *       *       /root/bin/webserver_check.sh