Monitoring websites with NAGIOS and custom python script

Nagios is excellent monitoring tool and python is very powerful scripting language. Lets take a look how we can put this 2 together to create our own website monitoring plug-in. We will monitor basic public http response via python httplib module. In our example NAGIOS is installed on CentOS 7, procedure should be the same for other distributions but directory may be different.



Canada colocation

nag

We assume you already have functioning NAGIOS deployment and able to monitor services and receive notifications.

1. First lets create our python script in the plug-in directory. You will need to adjust this script based on your requirement. At very least you will need to change websites being monitored.

vi /usr/local/nagios/libexec/check_websites.py
#!/usr/bin/env python
import sys
import httplib

# loope over sites and if anython but 200 or 301 shows sound alarm

for site_name in ["prolinuxhub.com", "prolinuxhub.com", "site2.com",  # REPLACE WITH YOUR WEBSITES
]:
    try:
        conn = httplib.HTTPConnection(site_name)
        conn.request("HEAD", "/")
        r1 = conn.getresponse()
        conn.close()
        website_return = r1.status
        if website_return != 200 and website_return != 301:
            print "Problem with " + site_name
	    sys.exit(2)           
      
    except Exception as e:
        print "Possibly server down " + site_name
	sys.exit(2)

2. Now lets make sure the script is executable

chmod +x /usr/local/nagios/libexec/check_websites.py

3. Define service by adding this to the end of localhost.cfg file

vi /usr/local/nagios/etc/objects/localhost.cfg
define service{
        use                             local-service       
        host_name                       localhost
        service_description             Check WEBSITES
        check_command                   check_websites
        notifications_enabled           1
        }

4. Define appropriate command in the command.cfg file

vi /usr/local/nagios/etc/objects/commands.cfg
define command{
        command_name    check_websites
        command_line    $USER1$/check_websites.py
        }

5. Run this script to make sure there is no errors returned

/usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg
........
Checking global event handlers...
Checking obsessive compulsive processor commands...
Checking misc settings...

Total Warnings: 0
Total Errors:   0

6. Restart nagios

service nagios restart 

This is very basic monitoring but it will let you know if one of the sites stop responding with proper codes