Automatic Web Server Monitoring

Hi there! Here’s another quick suggestion for all of you out there who have to deal with a lot of web server environments and need to make sure that they’re all alive and responsive. Sure there are all sorts of tools for server monitoring and performance tracking, but I found that most of the time you just need to know if the server is up & running. And of course you should be notified if it’s not. Here’s my short Python script that does just that. You will need to tweak it a little to use in your environment. First of all I’ve set the content threshold to 2000 Bytes which means that the expected length of the page content returned is no less than 2000 Bytes. If it’s below this value, one could assume that something’s fishy going on. You might want to change this value to something else depending on what your web server returns. Another thing that you’ll want to change is the servers dictionary in the main() method. The logic behind this is that each of the web servers is assigned a responsible person that you would need to inform if something is wrong with the server. You should list all your servers that need to be monitored and the responsible person’s e-mails. The final change is on the line where you instantiate the HeartbeatMonitor class. The first parameter admins is a list of e-mails of the people who will receive the notification if any of the servers are down. You can leave this list empty if you want, but I usually put my e-mail in there since I like to be in the loop. The second parameter mailServer is the SMTP server which will be used to send notifications so make sure this one is set correctly. This parameter is actually optional and localhost will be used as the default mail server if you decide to skip it.

#!/usr/bin/env python

import smtplib
import urllib2

"""
This script helps monitoring multiple servers and notifies
via email when something is wrong.
"""


__version__ = "0.1"
__author__ = "Andrius Miasnikovas"
__license__ = "psf"

class HeartbeatMonitor(object):
    admins = []
    mailServer = None
    threshold = 2000

    def __init__(self, admins, mailServer='localhost'):
        super(HeartbeatMonitor, self).__init__()
        self.mailServer = smtplib.SMTP(mailServer)
        self.mailServer.set_debuglevel(0)
        self.admins = admins

    def sendEmail(self, recipient, content):
        sender = 'noreply@hmonitor.net'
        print '-- Sending email message: ' + content
        recipient = recipient.strip()
        if len(recipient) > 0 and not self.admins.__contains__(recipient):
            self.admins.append(recipient)
        message = "From: %s\\r\\nTo: %s\\r\\nSubject: Warning: there's a problem with the server\\r\\n\\r\\n%s" \\
                  % (sender, ", ".join(self.admins), content)
        self.mailServer.sendmail(sender, self.admins, message)
        self.mailServer.quit()

    def check(self, servers):
        for (server, admin) in servers.items():
            try:
                h = urllib2.HTTPHandler(debuglevel=0)
                opener = urllib2.build_opener(h)
                print server, "-",
                page = opener.open(server)
                data = page.read()
                if page.code != 200 or len(data) < self.threshold:
                    print "UNKNOWN"
                    self.sendEmail(admin, 'Server '+server+' is responding, but state undetermined.')
                else:
                    print "UP"
            except:
                print "DOWN"
                self.sendEmail(admin, 'Server '+server+' is not responding')

def main():
    servers = {
            'https://server1.company.com'         : 'person.one@company.com',
            'http://server2.company.com/web/app'  : 'person.two@company.com',
    }

    hMonitor = HeartbeatMonitor(['admin@company.com'], 'smtp.company.com')
    hMonitor.check(servers)

if __name__ == "__main__":
    main()

After you make your alterations go ahead and run the script a couple of times to make sure it’s working. Then if you’re running it on a Linux box you could automate the process by adding it to the cron scheduler list. Simply run the following command

crontab -e

and add a line similar to this

*/30 * * * * /usr/local/bin/hmonitor.py

Where /usr/local/bin/hmonitor.py is the absolute path to this monitoring script and the part in front of it is the time when this script should be run. In this specific case the script will be run every 30 minutes, but you can change it to your liking. If you need more information on the crontab format which is used by the cron scheduler see the wiki page.

3 comments

  • Sara Bradfrod

    I hope this script will prove beneficial to keep our server/website up & running. Monitor Scout, a complete web monitoring solution provider has also launched its services across the globe which will not only give prior notifications but will also help in maintaining server/website health regularly.
    http://www.monitorscout.com
    please follow this link to sign up for free trial.

Leave a Reply

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


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>