Skip to content

Monitoring Website for Downtime

linux · python · server · By Madhurendra Sachan ·

Sometimes our in house server go down, But at production level we cannot take risk of 1min downtime, so we were supposed to monitor our server for downtime.
Although there are many cheap services available but i decided to do it my own way, I can use this script in my RPI to monitor even my internal services.

Below is python code, Which sends email if a server goes down and when it comes back online. Obviously you can add code to get more statistics like Logging to file, average response time, Monitoring page changes, Downtime etc.

import httplib
import time
from smtplib import SMTP

def send_email(to,subject,body,SERVER="smtp.gmail.com",PORT=587,USERNAME="something@gmail.com",PASSWORD="YourPassword"):
	smtp = SMTP(SERVER, PORT)
	smtp.ehlo()
	smtp.starttls()
	smtp.login(USERNAME, PASSWORD)
	headers = "\r\n".join(["from: " + USERNAME,
                       "subject: " + subject,
                       "to: " + to,
                       "mime-version: 1.0",
                       "content-type: text/html"])
                    
	content = headers + "\r\n\r\n" + body
	smtp.sendmail(USERNAME, to, content)



def get_status_code(host,path="/"):
	try:
		conn = httplib.HTTPConnection(host,timeout=10)
		conn.request("HEAD",path)
		return conn.getresponse().status
	except StandardError:
		return 0


def get_site_status(host):
	start = time.time()
	status = False
	code = get_status_code(host)
	#if found, temp redirect, permanent redirect.
	if code in (200,302,301):
		status = True
	return status, time.time()-start,code


def check_internet():
	return get_site_status("google.com")

def check_status():
	toMonitor = ["tikaj.com"]
	down = []
	email = ""
	while True: 
		for value in toMonitor:
			st = "Checking %s..." %value

			#give enough space so that status code can be idented.
			while(len(st)<40):
				st += " "
			print st,

			status,rtime,code = get_site_status(value)
			print "[%s]" %code,

			if status==False :
				if check_internet()[0] == True :
					print "[Server down]"
					
					#if not present in Server down list. Add for email and add to down list.
					if value not in down:
						down.append(value)
						email += st + "<b>[SERVER_DOWN]</b><br/>"
				else:
					print "[Internet Fail]"
			else: 
				# if in down list compose mail that server is up.
				if value in down:
					email += st + "<b>[%fs]</b>" %rtime
					down.remove(value)
				print "[%fs]" %rtime


		if(len(email)>10):

			print "Sending alert email..."
			send_email("myemail@gmail.com","ServerDown!","<pre>%s</pre>" %email)
			email = ""

		time.sleep(60) #sleep for 60s

if __name__ == '__main__':
	check_status()

After saving code to server use cron job to start run script on every boot.

Edit crontab using `sudo crontab -e` and then add following line to file.

`@reboot screen -dmS monitor python /root/monitor.py &> /dev/null`

Above command starts a `screen` session named monitor and forwards error of screen to null.
Incase you want to see output of monitor.py use `screen -r monitor`.
You can also add it simply without screen like
`@reboot python /root/monitor.py &`

If you have some suggestions comment.

IOT Push Button (Like Amazon Dash)

Amazon Dash button is an incredible piece of hardware and another example of “applied engineering” in Amazon, just like Kindle. The inspiration for this project isn’t directly derived from amazon dash, I wasn’t aware of it until I started digging the internet but at end, I had to set the performance goal to Amazon dash, because

arduino · linux · server · snippets ·

Cheap BLE : JDY-08

Disclaimer : This post is based on my experience which is completely subjective, in no way I am promoting any application or product 😉 I have been trying to get my hands into BLE4.0 modules since long. As always I was looking for small, cheap solution, JDY-08 was one of solution I came across –

arduino · linux ·

Adding a display over network !

You are doomed if your laptop has only one HDMI Port & you are running Linux in that box. Unlike windows – where there are tons of easy to run solution, & there are still tons of solutions if you have big numbers in your pocket. Certainly – I neither wish to spend money on external VGA/HDMI

linux · server · snippets ·