[PYTHON] Regularly monitor the HTTP response of the web server

If the web server goes down, it will notify you by gmail

I wrote such a script. ** (However, I only check while the computer is running. Should I run it regularly on a PC that is running all day or on another server?) **

Other than gmail, you can use it by editing the SMTP server and port number.

It shouldn't happen that the web server is down when you notice it, but it happens occasionally. I don't have the energy or resources to introduce Zabbix, or it's a little troublesome, so this time I decided to check it regularly from my home PC. By the way, I tried to record the result in the local storage.

script

The script below sends an HTTP GET and if something goes wrong, A Python script that will notify you by email.

We have confirmed the operation on Python3.3 and Windows. If you have a Mac or a different Python version, please fix it in a timely manner.

(We are not responsible for any damage caused by executing the script, so please use it at your own risk.)

webtest.py


#!/usr/bin/python
# coding: UTF-8
#Web server monitoring tool
import http.client,datetime,os

#============Setting items==============
#Gmail account
gmail_sender = 'With your [email protected]'
#Gmail password
gmail_passwd = 'Your password'
#Error mail destination
gmail_to = 'Soshinsaki @ email address'
#Email subject
mail_subject =  'There is a server error'
#Server to check
servers = ("www.Your Saito 1.com","www.Your site 2.net")
#Log save destination directory(Relative path)
log_dir = "webtestlog"
#=================================

import smtplib
from email.mime.text import MIMEText

#send e-mail
def sendmail(data):
	global gmail_sender,gmail_passwd,gmail_to,mail_subject
	TEXT = data
	#Sign in
	server = smtplib.SMTP('smtp.gmail.com', 587)
	server.ehlo()
	server.starttls()
	server.login(gmail_sender, gmail_passwd)

	message = MIMEText(data,"plain","UTF-8")
	message["Subject"] = mail_subject
	message["From"] = gmail_sender
	message["To"] = gmail_to

	try:
	    server.sendmail(gmail_sender, [gmail_to], message.as_string())
	    print ('email sent')
	except Exception as e:
		print (e)
		print ('error sending mail')

	server.quit()


result = ""
error_detected = False


#The format of the result. If you customize this, you can add more detailed information.
def format_result(address,response):
	return address +"  "+ str(response.status) + "   " + response.reason

#Check the root directory
def checkroot(address):
	global result,error_detected
	conn = http.client.HTTPConnection( address )
	try:
		conn.request( "GET", "/" )
	except:
		result = result + address + " CANNOT GET\n"
		error_detected = True
		return
	response = conn.getresponse()
	if response.status != 200:
		error_detected = True
	result = result + format_result(address,response) + "\n"
	conn.close()

#Check all servers here
for each in servers:
	checkroot(each)


if not os.path.isdir(log_dir):
	os.mkdir(log_dir)

now = datetime.datetime.now()
#Embed time information
result = str(now) + "\n" + result
#Record response
filename = log_dir+"\log_"+now.strftime("%y-%m-%d")+".txt";
f = open(filename, 'a') #Addendum mode
f.write(result) #result
f.close()


#Send an email if there is an error
if error_detected:
	sendmail(result);

Execution result

Right now, I dare to make a mistake in the URL and generate an error, but if a 500 error occurs or an error occurs when executing HTTP GET, You will receive an email like this.

result.png

Batch file creation

I don't think the python script could be executed directly, so create a batch file. (Suppose the webtest.py script is located in C: \ bin.)

webtest.bat


cd C:\bin
python webtest.py

If you don't cd, you won't find webtest.py! Please note that the error will occur.

Scheduler

Try running the above script once, and if it works correctly, schedule it next. This time I decided to run it regularly with the Windows task scheduler.

Control Panel> Search by "Schedule"> Schedule Task

n.png

When the task scheduler starts, create it appropriately with "Create basic task". Keep the trigger "every day". (You can change it later in a short time) In Select Program, select the previous batch file.

Check every X minutes

Edit the trigger. fsa.png

Make it background

It's noisy to get a glimpse of the command prompt every time, so hide it.

On the properties screen, type Change User or Group> SYSTEM and OK It is OK if "User account used when executing the task:" becomes "NT AUTHORITY \ SYSTEM".

aa.png

Recommended Posts

Regularly monitor the HTTP response of the web server
Django returns the contents of the file as an HTTP response
The story of remounting the application server
Visualize the response status of the census 2020
Start the web server in the current directory
I tried the asynchronous server of Django 3.0
[Zabbix] Does the response time of Web monitoring include image files, etc.?
Let's summarize the construction of NFS server
Change the destination batfish server of pybatfish
Publish the current directory on the web server
Launch an HTTP server in the current directory
[Python3] Take a screenshot of a web page on the server and crop it further
The story of launching a Minecraft server from Discord
Summarize the knowledge of reading Go's HTTP implementation ~ Slice ~
Summarize the knowledge of reading Go's HTTP implementation ~ Channel ~
Visualization of the connection between malware and the callback server
Execute the command on the web server and display the result
Create a web server in Go language (net / http) (1)
Get the URL of the HTTP redirect destination in Python
HTTP server and HTTP client using Socket (+ web browser) --Python3
I tried to rewrite the WEB server of the normal Linux programming 1st edition with C ++ 14
Fixed-point observation of specific data on the Web by automatically executing the Web browser on the server (Ubuntu16.04) (1) -Web browser installation-
Command collection (server edition) that you should know by isolating the cause of failure response