python2.5Fully configurable multi-host script with logging and email alerting.

This is a simple little python script that opens a socket, passes some information, and then watches for a particular return.  I built in logging and email notifications.  It writes both successful and non-successful attempts, and all exceptions to the log, and emails if it can’t open the socket or if the delay is too long, which is also something you can set.  It will handle multiple IP addresses, multiple ports, and multiple request strings, also the log roller is built in (500MB worth).  It uses an SMTP server to send the mail, so if your mail server requires authentication, this won’t work without modification.  It is also setup to pass multiple strings to the to the socket connection.

IP / Port / String rotation works like this:

ip’s = 1.1.1.1, 1.1.1.2, 1.1.1.3, 1.1.1.4
ports = 00001, 00002
strings = requestA, requestB

1.1.1.1:00001 requestA
1.1.1.1:00001 requestB
1.1.1.1:00002 requestA
1.1.1.1:00002 requestB
1.1.1.2:00001 requestA
1.1.1.2:00001 requestB
1.1.1.2:00002 requestA
1.1.1.2:00002 requestB
1.1.1.3:00001 requestA

and so on….

This was my first attempt at python, so I’m sure the code could be prettier.  Open to comments as long as their constructive.  This script fills a very specific need for me… there may have been better ways, but this is what I needed it to do.

(if the code isn’t displaying properly, try a shift-refresh on the page)

 

#!/usr/bin/python

import socket
import logging
import time
import random
import datetime
import logging
import logging.handlers
import smtplib

okResponseDelay = 1 
acceptableDelay = datetime.timedelta(seconds=okResponseDelay)
ipAddress = ['xxx.xxx.xxx.xxx', 'xxx.xxx.xxx.xxx', 'xxx.xxx.xxx.xxx'] 
response = "Keyword to watch for in the response"
portList = [xxxxx, xxxxx]
requestList = ['string', 'string'] 
t = 5 
host = "smtp.domain.com"
sender = 'email@domain.com'
receiver = 'email@domain.com'
msg = """From: Display Name <email@domain.com>
To: ToWhom <email@domain.com>
Subject: Text Goes Here """
msgDelay = """From: Display Name <email@domain.com>
To: ToWhom <email@domain.com>
Subject: Text Goes Here """
logName = '/path/to/log'
logging.basicConfig(level=logging.INFO, filename=logName)
logger = logging.getLogger('myLogger')
logger.setLevel(logging.INFO)
formatter = logging.Formatter("\n##### {80e463235c561985fcb9d065cb7af58becf1df7010d7a45bb4eb7315e5a8b304}(asctime)s\t")
handler = logging.handlers.RotatingFileHandler(logName, maxBytes=1024*1024*10, backupCount=5)
handler.setFormatter(formatter)
logger.addHandler(handler)

for ip in ipAddress:
	for port in portList:
		for request in requestList:
			s = socket.socket()
			timeStart = datetime.datetime.now()
			try:
				s.connect((ip, port))
			except Exception, e: 
				logger.exception("\n ::: Connection Error ::: \n")
				s.close()
				try: 
					email = smtplib.SMTP(host)
					email.sendmail(sender, receiver, msg)	
				except Exception, email:
					logger.exception("\n ::: Sent Email Error ::: \n")
				continue
			s.send((request))
			r = s.recv(1024)
			s.close()
			timeEnd = datetime.datetime.now()
			responseTime = timeEnd - timeStart 
			try:
				if response in r:
					logger.info(' Connection Successful ')
			except Exception, e:
				logger.exception("\n ::: Service Error ::: \n")
			try:
				if responseTime > responseTime + acceptableDelay:
					email = smtplib.SMTP(host) 
					email.sendmail(sender, receiver, msgDelay)
					logger.info(' Extended Delay - Email Sent') 
			except Exception, e:
				logger.exception("\n ::: Extended Delay Email Failed ::: \n")
			time.sleep(t)

 

 

Leave a reply

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