Checking your site remains up

Since I just wanted to check the email and webserver remained up I constructed a noddy python script.

This is it with the actual addresses modified. Feel free to use it as you want. I just have it running every half hour on a cron job.


0,30 * * * * /home/colin/check_site.py


#!/usr/bin/python

import httplib
import smtplib
import poplib

def send_email(http_error, pop_error):
    subject = ""
    reason = ""
    if http_error == "" :
        subject = "Email down - website up"
        reason = pop_error
    elif pop_error == "":
        subject = "Website down - email up"
        reason = http_error
    else:
        subject = "Website and email down"
        reason = http_error + "\r\nEmail - " + pop_error
    try:
        server = smtplib.SMTP("smtp.myhost.com")
        from_add = "from@someserver.com"
        to_add = ("my.email@server.com")
        message = "Subject: " + subject + "\r\n"
        message += "To: Name <my.email@server.com>\r\n"
        message += "From: Name <from@someserver.com>\r\n"
        message += "\r\n"
        message += "Server down - " + reason
        server.sendmail(from_add, to_add, message)
        server.quit()
        print "Sent email"
    except:
        print "Unable to send"
        # guess we must not have a connection,
        # don't bother storing the email because
        # the problem is most likely at our end.

http_error = ""
pop_error = ""

try:
    connection = httplib.HTTPConnection("www.ourserver.com")
    connection.request("HEAD", "/")
    response = connection.getresponse()
    if response.status != 200:
        print response.status, response.reason 
        send_email("Invalid response - %d %s" % (response.status, response.reason))
    connection.close()

except Exception, inst:
    http_error = "Unable to connect " + inst.message

try:
    pop = poplib.POP3("pop3.ourserver.com")
    pop.quit()
except Exception, inst:
    pop_error = "Unable to connect " + inst.message

if not (http_error == "" and pop_error == ""):
    send_email(http_error, pop_error)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s