Python easy server checker with email notification

In this article, we will build a simple server checker Python script that will notify by email if servers utils will fail on response. Let’s get started.
For this script, we will import the following Python classes.

import urllib.request
import MySQLdb
import socket
import subprocess, platform
import smtplib, ssl
import datetime

Check PING

The function that will check PING windows or Linux command return string ‘True‘ or ‘False‘ if ping failed:

# check ping
def check_ping(sHost):
    try:
        output = subprocess.check_output("ping -{} 1 {}".format('n' if platform.system().lower()=="windows" else 'c', sHost), shell=True)
    except Exception as e:
        return 'False'
    else:
    	return 'True'

Check Database

The function that will check database connection on return string ‘True‘ or ‘False‘ if the connection failed:

#check DB
def check_db(host, user, passwd, db, port):
  # Connect to the MySQL database
  try:
  		db = MySQLdb.connect(host = host, user = user, passwd = passwd, db = db, port = port)
  except:
    return 'False'
  else:
    return 'True'

Check Web

The function that will check the web server response on return string of server type (Apache, Windows IIS, or any other) or ‘False‘ if the connection failed:

#check web apache, iis 
def check_web(host):
  try:
    response = urllib.request.urlopen(host, timeout=10)
  except Exception as e:
    return 'False'
  except timeout:
    return 'False'
  else:
    return response.headers['Server']

Sent Email

The function that will send an email if any failure message it will return the string ‘False‘ if success return ‘True‘:

# sent email with notification
def snet_email(body, host, receiver):
  port = 465  # For SSL
  smtp_server = "mail.email.com"
  sender_email = "test@email.com"  # Enter your address
  receiver_email = receiver # Enter receiver address
  password = "password"
  subject = 'SERVERS ALER !!! - easyvoipcall notification - {}'.format(host)

  message = "From: %s\r\n" % sender_email + "To: %s\r\n" % receiver_email + "Subject: %s\r\n" % subject + "\r\n" + body + "\r\n" + "!!! Please check immediately !!!"

  context = ssl.create_default_context()
  try:
    with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver_email, message)
        server.quit()
  except Exception as e:	    
    return 'False'
  else:
    return 'True'

Check SSL

The function that will check SSL expiration on the return we will get the value of how many days SSL will be valid:

def check_ssl(hostname, port):
  ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z'

  context = ssl.create_default_context()
  conn = context.wrap_socket(
    socket.socket(socket.AF_INET),
    server_hostname=hostname,
  )
  # 3 second timeout because Lambda has runtime limitations
  conn.settimeout(3.0)

  conn.connect((hostname, port))
  ssl_info = conn.getpeercert()
  # parse the string from the certificate into a Python datetime object
  expirationDate = datetime.datetime.strptime(ssl_info['notAfter'], ssl_date_fmt)
  now = datetime.datetime.now()
  delta = expirationDate - now
  return delta

Run program

Now we can run our functions and prepare an email message body for any failures:

#run functions
message_body = ''

#check the database
host = 'localhost'
port = 3306
db_check = check_db(host, 'db_user', 'db_password', 'database', port)
if db_check == 'False':
  message_body = 'SERVER: ' + host + "\r\nDB: " + "Failed\r\n"

#check the PING
host = 'localhost'
ping_check = check_ping(host)
if ping_check == 'False':
  message_body += 'SERVER: ' + host + "\r\nPING: " + "Failed\r\n"

#check the web server
web_check = check_web('http://localhost/')
if web_check == 'False':
  message_body += 'SERVER: https://sip1.easyvoipcall.com/VUC' + "\r\nWEB: " + "Failed\r\n"

#check the email
check_email = 	snet_email('Hello this is test email to check if all is fine with SMTP: test@email.com', 'localhost', 'info@in4system.com')
if check_email != 'True':
  message_body += 'Email:  test@email.com - Failed\r\n'

#check the ssl
hostname = 'in4system.com'
port = 443
d = check_ssl(hostname, port)
if d.days < 14:
  message_body += 'SSL CERT: in4system.com - Expired in {}\r\n'.format(d.days)

#sent email notification
if message_body != '':
  sent_message = snet_email(message_body, 'localhost', 'support@in4system.com')

That is it. We have now very simple server checker Python script that will notify us with email if any of the server services will be down. I hope it will help you in your job to get the information about your server. Please leave a comment for any doubts or queries.

, ,

Related Posts

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.

Menu