Commit 5a331840 authored by Daniel Armbruster's avatar Daniel Armbruster Committed by thomas.forbriger
Browse files

Renamed csbackmail.py to csbackntfy.py. Prepared for nagios output.

This is a legacy commit from before 2015-05-18.
It may be incomplete as well as inconsistent.
See COPYING.legacy and README.history for details.


SVN Path:     http://gpitrsvn.gpi.uni-karlsruhe.de/repos/TFSoftware/trunk
SVN Revision: 4393
SVN UUID:     67feda4a-a26e-11df-9d6e-31afc202ad0c
parent 9e0d50b6
#!/usr/bin/env python
## @file csbackmail.py
## @file csbackntfy.py
# @brief Checking the log entries and send a email containing the current
# status.
#
......@@ -32,7 +32,8 @@
# Copyright (c) 2012 by Daniel Armbruster
#
# REVISIONS and CHANGES
# 05/12/2012 V0.1 Daniel Armbruster
# 05/01/2012 V0.1 Daniel Armbruster
# 12/01/2012 V0.2 provide nagios status line
#
# =============================================================================
"""
......@@ -50,7 +51,7 @@ import csbacklog
from email.mime.text import MIMEText
from collections import deque
__version__ = "V0.1"
__version__ = "V0.2"
__subversion__ = "$Id$"
__license__ = "GPLv2"
__author__ = "Daniel Armbruster"
......@@ -64,7 +65,7 @@ class Error(Exception):
self.msg = msg
def display(self):
sys.stderr.write("csbackmail (ERROR): " + self.msg + "\n")
sys.stderr.write("csbackntfy (ERROR): " + self.msg + "\n")
sys.stderr.write("triggered in line: " + self.line + "\n")
......@@ -73,12 +74,14 @@ class Usage(Error):
def display(self):
usage_text = "Version: "+__version__+"\nLicense: "+__license__+ \
"\n"+__subversion__+"\nAuthor: "+__author__+ """
Usage: csbackmail [-v|--verbose] [-d|--debug] [-l|--logging] -P|--port ARG
Usage: csbackntfy [-v|--verbose] [-d|--debug] [-l|--logging] -P|--port ARG
-H|--host ARG -u|--username ARG -p|--password ARG
-r|--receiver ADDRESS [-r|--receiver ADDRESS [...]]
-s|--sender ADDRESS [PATH [PATH [...]]]
or: csbackmail -h|--help\n"""
sys.stderr.write("csbackmail [line "+self.line+"]: "+self.msg+"\n")
or: csbackntfy [-v|--verbose] [-d|--debug] [-l|--logging] -n|--nagios
[PATH [PATH [...]]]
or: csbackntfy -h|--help\n"""
sys.stderr.write("csbackntfy [line "+self.line+"]: "+self.msg+"\n")
sys.stderr.write(usage_text)
# -----------------------------------------------------------------------------
......@@ -88,11 +91,13 @@ def help():
"""
help_text = "Version: "+__version__+"\nLicense: "+__license__+"\n"+ \
__subversion__+"\nAuthor: "+__author__+"""
Usage: csbackmail [-v|--verbose] [-d|--debug] [-l|--logging] -P|--port ARG
Usage: csbackntfy [-v|--verbose] [-d|--debug] [-l|--logging] -P|--port ARG
-H|--host ARG -u|--username ARG -p|--password ARG
-r|--receiver ADDRESS [-r|--receiver ADDRESS [...]]
-s|--sender ADDRESS [PATH [PATH [...]]]
or: csbackmail -h|--help
or: csbackntfy [-v|--verbose] [-d|--debug] [-l|--logging] -n|--nagios
[PATH [PATH [...]]]
or: csbackntfy -h|--help
-------------------------------------------------------------------------------
-v|--verbose Be verbose.
-h|--help Display this help.
......@@ -106,6 +111,8 @@ def help():
-H|--host ARG Hostname of the SMTP server.
-u|--username ARG Username for SMTP server login.
-p|--password ARG Password for SMTP server login.
-n|--nagios Use csbackntfy in it's nagios mode and print the current
status in a simple line to stdout.
PATH Path(s) of the logfile(s) to check. If not specified the
logfiles in /var/log/ were investigated.
"""
......@@ -114,7 +121,7 @@ def help():
# -----------------------------------------------------------------------------
def main(argv=None):
# configure logger
logger = csbacklog.CsbackLog('csbackmail')
logger = csbacklog.CsbackLog('csbackntfy')
console = logging.StreamHandler()
console.setFormatter(logging.Formatter( \
......@@ -125,11 +132,11 @@ def main(argv=None):
argv = sys.argv
try:
try:
opts, args = getopt.getopt(argv[1:], "vhdlr:s:P:H:u:p:", ["help", \
opts, args = getopt.getopt(argv[1:], "vhdlr:s:P:H:u:p:n", ["help", \
"verbose", "debug", "logging", "receiver=", "sender=", "port=", \
"host=", "username=", "password="])
"host=", "username=", "password=", '--nagios'])
except getopt.GetoptError as err:
raise Usage(132,err.msg)
raise Usage(139,err.msg)
verbose = False
debugMode = False
receivers = []
......@@ -138,6 +145,7 @@ def main(argv=None):
host = ''
username = ''
password = ''
nagiosMode = False
# collect commandline arguments
for opt, arg in opts:
if opt in ("-v", "--verbose"):
......@@ -163,8 +171,10 @@ def main(argv=None):
username = arg
elif opt in ("-p", "--password"):
password = arg
elif opt in ("-n", "--nagios"):
nagiosMode = True
else:
raise Usage(168,"Unhandled option chosen.")
raise Usage(177,"Unhandled option chosen.")
if verbose or debugMode:
logger.addHandler(console)
......@@ -180,30 +190,8 @@ def main(argv=None):
if None != re.match('^csback\.log$', logfile)]
logFilePathes.reverse()
else:
raise Usage(183,"Invalid argument(s).")
raise Usage(193,"Invalid argument(s).")
logger.getLogger().debug("Checking email addresses.")
if 0 == len(sender):
raise Usage(187, "Email address of sender missing.")
if None == re.match( \
'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$', sender):
raise Error(190, "Email address of sender not valid.")
if 0 == len(receivers):
raise Usage(192, "Email address of receiver missing.")
for add in receivers:
if None == re.match( \
'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$', add):
raise Error(196, "Email address of receiver not valid.")
if 0 == len(host):
raise Usage(198, "Hostname missing.")
if 0 == len(username):
raise Usage(200, "Username missing.")
if 0 == len(password):
raise Usage(202, "Password missing.")
if -1 == port:
raise Usage(202, "Port missing.")
infoDeque = deque(maxlen=10)
warningDeque = deque(maxlen=10)
errorList = []
......@@ -224,86 +212,118 @@ def main(argv=None):
else:
logger.getLogger().info("Illegal line in logfile found.")
except IOError as err:
raise Error(218, "Error while reading logfiles.")
raise Error(215, "Error while reading logfiles.")
logger.getLogger().debug("Finished reading logfile(s).")
# prepare email
logger.getLogger().debug("Preparing email content ...")
msg = '============================\n'
msg += 'csbackmail.py logfile status\n'
msg += '============================\n'
msg += 'Number of read logfiles: {0}\n\n'.format(len(logFilePathes))
infoList = list(infoDeque)
subject = ''
if len(infoList):
logger.getLogger().debug("Adding INFO logfile lines to mail content.")
subject = 'csback report - severity: INFO'
msg += '--------------------------\n'
msg += 'INFO entries (last {0}):\n'.format(len(infoList))
msg += '--------------------------\n'
for line in infoList:
msg += line
warningList = list(warningDeque)
if len(warningList):
logger.getLogger().debug( \
"Adding WARNING logfile lines to mail content.")
subject = 'csback report - severity: WARNING'
msg += '--------------------------\n'
msg += 'WARNING entries (last {0}):\n'.format(len(warningList))
msg += '--------------------------\n'
for line in warningList:
msg += line
if len(errorList):
logger.getLogger().debug("Adding ERROR logfile lines to mail content.")
subject = 'csback report - severity: ERROR'
msg += '--------------------------\n'
msg += 'ERROR entries:\n'
msg += '--------------------------\n'
for line in errorList:
msg += line
if len(criticalList):
logger.getLogger().debug( \
"Adding CRITICAL logfile lines to mail content.")
subject = 'csback report - severity: CRITICAL'
msg += '--------------------------\n'
msg += 'CRITICAL entries:\n'
msg += '--------------------------\n'
for line in criticalList:
msg += line
mail = MIMEText(msg)
mail['Subject'] = subject
mail['From'] = 'csback <'+sender+'>'
mail['To'] = receivers[0]
if 1 < len(receivers):
mail['CC'] = ', '.join(receivers[1:])
logger.getLogger().debug("Finished preparation of email content.")
if nagiosMode:
raise Usage(219, "nagios option not implemented yet.")
if len(criticalList):
sys.stdout.write("CSBACK CRITICAL")
elif len(errorList):
sys.stdout.write("CSBACK ERROR")
elif len(warningDeque):
sys.stdout.write("CSBACK WARNING")
else:
sys.stdout.write("CSBACK OK")
else:
logger.getLogger().debug("Checking email addresses.")
if 0 == len(sender):
raise Usage(231, "Email address of sender missing.")
if None == re.match( \
'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$', sender):
raise Error(234, "Email address of sender not valid.")
if 0 == len(receivers):
raise Usage(236, "Email address of receiver missing.")
for add in receivers:
if None == re.match( \
'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$', add):
raise Error(240, "Email address of receiver not valid.")
# send mail
logger.getLogger().debug("Sending email.")
try:
session = smtplib.SMTP(host=host, port=port)
session.starttls()
session.login(username, password)
session.sendmail(sender, receivers, mail.as_string())
except smtplib.SMTPRecipientsRefused:
session.quit()
logger.getLogger().warning( \
"All recipients were refused. Nobody got the mail.")
except smtplib.SMTPHeloError:
session.quit()
logger.getLogger().warning( \
"The server didn't reply properly to the HELO greeting.")
except smtplib.SMTPSenderRefused:
session.quit()
logger.getLogger().warning( \
"The server didn't accept the address '%s'", sender)
except smtplib.SMTPDataError:
session.quit()
logger.getLogger().warning( \
"The server replied with an unexpected error code.")
else:
session.quit()
if 0 == len(host):
raise Usage(243, "Hostname missing.")
if 0 == len(username):
raise Usage(245, "Username missing.")
if 0 == len(password):
raise Usage(247, "Password missing.")
if -1 == port:
raise Usage(249, "Port missing.")
# prepare email
logger.getLogger().debug("Preparing email content ...")
msg = '============================\n'
msg += 'csbackntfy.py logfile status\n'
msg += '============================\n'
msg += 'Number of read logfiles: {0}\n\n'.format(len(logFilePathes))
infoList = list(infoDeque)
subject = ''
if len(infoList):
logger.getLogger().debug("Adding INFO logfile lines to mail content.")
subject = 'csback report - severity: INFO'
msg += '--------------------------\n'
msg += 'INFO entries (last {0}):\n'.format(len(infoList))
msg += '--------------------------\n'
for line in infoList:
msg += line
warningList = list(warningDeque)
if len(warningList):
logger.getLogger().debug( \
"Adding WARNING logfile lines to mail content.")
subject = 'csback report - severity: WARNING'
msg += '--------------------------\n'
msg += 'WARNING entries (last {0}):\n'.format(len(warningList))
msg += '--------------------------\n'
for line in warningList:
msg += line
if len(errorList):
logger.getLogger().debug("Adding ERROR logfile lines to mail content.")
subject = 'csback report - severity: ERROR'
msg += '--------------------------\n'
msg += 'ERROR entries:\n'
msg += '--------------------------\n'
for line in errorList:
msg += line
if len(criticalList):
logger.getLogger().debug( \
"Adding CRITICAL logfile lines to mail content.")
subject = 'csback report - severity: CRITICAL'
msg += '--------------------------\n'
msg += 'CRITICAL entries:\n'
msg += '--------------------------\n'
for line in criticalList:
msg += line
mail = MIMEText(msg)
mail['Subject'] = subject
mail['From'] = 'csback <'+sender+'>'
mail['To'] = receivers[0]
if 1 < len(receivers):
mail['CC'] = ', '.join(receivers[1:])
logger.getLogger().debug("Finished preparation of email content.")
# send mail
logger.getLogger().debug("Sending email.")
try:
session = smtplib.SMTP(host=host, port=port)
session.starttls()
session.login(username, password)
session.sendmail(sender, receivers, mail.as_string())
except smtplib.SMTPRecipientsRefused:
session.quit()
logger.getLogger().warning( \
"All recipients were refused. Nobody got the mail.")
except smtplib.SMTPHeloError:
session.quit()
logger.getLogger().warning( \
"The server didn't reply properly to the HELO greeting.")
except smtplib.SMTPSenderRefused:
session.quit()
logger.getLogger().warning( \
"The server didn't accept the address '%s'", sender)
except smtplib.SMTPDataError:
session.quit()
logger.getLogger().warning( \
"The server replied with an unexpected error code.")
else:
session.quit()
except Usage as err:
err.display()
......@@ -320,4 +340,4 @@ def main(argv=None):
if __name__ == "__main__":
sys.exit(main())
# ----- END OF csbackmail.py -----
# ----- END OF csbackntfy.py -----
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment