Skip to content

Instantly share code, notes, and snippets.

@Eun
Last active September 5, 2015 13:05
Show Gist options
  • Save Eun/5b35a615b490462f2823 to your computer and use it in GitHub Desktop.
Save Eun/5b35a615b490462f2823 to your computer and use it in GitHub Desktop.
Simple service monitor
#!/usr/bin/env python
"""ssm.py: Simple service monitor."""
__author__ = "Eun"
__copyright__ = "Copyright 2015, Eun"
__license__ = "GPL"
__version__ = "1.0.0"
# Service Configuration
###########################################################################
#
# Enter all services you need to check in the following format
# "ServiceName": "hostname:port"
# Seperate each entry with a comma
# Leave the list empty to omit the check
# Example:
# IPv4Services = {"FTP": "example.com:21", "HTTP": "example.com:80", "HTTPS": "example.com:443"}
# IPv6Services = {"HTTP": "example.com:80", "HTTPS": "example.com:443"}
# Check FTP, HTTP & HTTPS in IPv4 mode
# Only check HTTP & HTTPS in IPv6 mode, FTP wont be checked in IPv6!
# Hint: You could also avoid double typing by coping the list:
# IPv4Services = {"FTP": "example.com:21", "HTTP": "example.com:80", "HTTPS": "example.com:443"}
# IPv6Services = IPv4Services.copy()
#
IPv4Services = {"HTTP": "example.com", "HTTPS": "example.com"}
IPv6Services = IPv4Services.copy()
# Email Configuration
###########################################################################
#
# Should SSM send a mail?
SendMail = True
# Set the smtp server to send mails from
MailServerHost = "smtp.example.com"
MailServerPort = 465
# Use SSL?
MailServerSSL = True
# Use StartTLS
MailStartTLS = False
# smtp username
MailUser = "nobody"
# smtp password
MailPassword = "password"
# Title to use when something is down
MailTitleDown = "[SSM] Some Services are down!"
# Title to use when everything is ok
MailTitleUp = "[SSM] All Services are Up!"
# Sender
MailFrom = "[email protected]"
# Recipent list
# Format ["[email protected]", "[email protected]", ..., "[email protected]" ]
MailTo = ["[email protected]"]
# AdditionalInfo to put in the mail
# Good for IP Address or other details.
AdditionalInfo = ""
# Cronjob Configuration
###########################################################################
#
# The best is if you run this script in a cronjob, lets say every 5 minutes
# and every 24 hours to make sure all services are up:
#
# */5 * * * * python ssm.py >/dev/null 2>&1 # Run every 5 minutes
# * 3 * * * python ssm.py -f >/dev/null 2>&1 # Run every 24 hours (3am)
#
###########################################################################
# Configuration End
import sys
import socket
import smtplib
import datetime
import getopt
def testTCP(proto, host, port):
if (proto == "IPv4"):
proto = socket.AF_INET
else:
proto = socket.AF_INET6
s = socket.socket(proto, socket.SOCK_STREAM)
try:
s.connect((host, port))
s.close()
return True
except Exception, e:
return False
def main():
forceMail = False
try:
optlist, args = getopt.getopt(sys.argv[1:], "hfv", ["help", "force", "version"])
for o, a in optlist:
if o in ("-f", "--forced"):
forceMail = True
elif o in ("-h", "--help"):
print "usage: ssm.py [option]"
print "Options:"
print "-f, --force force the sending of a mail even if everything is up"
print "-h, --help shows this help"
print "-v, --version shows the version"
print ""
print "SimpleServiceMonitor {0}".format(__version__)
return 1
elif o in ("-v", "--version"):
print "SimpleServiceMonitor {0}".format(__version__)
return 1
except:
pass
ServicesList = {"IPv4": IPv4Services, "IPv6": IPv6Services}
OutputList = []
Failures = 0
for IPvX,Services in ServicesList.iteritems():
for Key,Value in Services.iteritems():
conn = Value.split(':')
service = "{0}({1}, {2})".format(Key, IPvX, Value)
if (not testTCP(IPvX, conn[0], int(conn[1]))):
service = "DOWN: {0}".format(service)
print service
OutputList.append(service)
Failures = Failures + 1
else:
service = "UP: {0}".format(service)
print service
OutputList.append(service)
if (SendMail and (Failures > 0 or forceMail)):
if (Failures > 0):
MailTitle = MailTitleDown
headLine = "Some services have failed to respond:"
else:
MailTitle = MailTitleUp
headLine = "All services are up:"
if (len(AdditionalInfo) > 0):
AdditionalInfoMsg = "Additional Info:\n{0}\n\n".format(AdditionalInfo)
else:
AdditionalInfoMsg = ""
msg = '\n\t'.join(OutputList)
msg = 'Subject: {0}\n\n{1}\n\t{2}\n\n{3}ServerTime: {4}\nSimpleServiceMonitor.py {5}'.format(MailTitle, headLine, msg, AdditionalInfoMsg, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), __version__)
try:
if (MailServerSSL):
server = smtplib.SMTP_SSL(MailServerHost, MailServerPort)
else:
server = smtplib.SMTP(MailServerHost, MailServerPort)
server.ehlo()
if (MailStartTLS):
server.starttls()
if (len(MailUser) > 0):
server.login(MailUser, MailPassword)
server.sendmail(MailFrom, MailTo, msg)
server.quit()
except Exception, e:
print "Error on sending mail!: "
print e
if (Failures > 0):
return 1
else:
return 0
if __name__ == "__main__":
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment