Commit 956ea11f authored by Daniel Armbruster's avatar Daniel Armbruster Committed by thomas.forbriger
Browse files

Implementation of source:tfsoftware/trunk/src/python/csback/

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.

Not tested yet.

SVN Path:
SVN Revision: 4343
SVN UUID:     67feda4a-a26e-11df-9d6e-31afc202ad0c
parent 312907cf
#!/usr/bin/env python
## @file
# @brief
# @brief Checking the log entries and send a email containing the current
# status.
# -----------------------------------------------------------------------------
# $Id$
# @author Daniel Armbruster
# \date 11/09/2011
# \date 05/01/2012
# Purpose:
# Purpose: Checking the log entries and send a email containing the current
# status.
# ----
# This file is part of csback.
......@@ -27,13 +29,251 @@
# along with csback. If not, see <>.
# ----
# Copyright (c) 2011 by Daniel Armbruster
# Copyright (c) 2012 by Daniel Armbruster
# 11/09/2011 V0.1 Daniel Armbruster
# 05/12/2012 V0.1 Daniel Armbruster
# =============================================================================
Script to check logfiles and send an email.
import getopt
import os
import sys
import re
import smtplib
import logging
import csbacklog
from email.mime.text import MIMEText
from collections import deque
# ----- END OF -----
\ No newline at end of file
__version__ = "V0.1"
__subversion__ = "$Id$"
__license__ = "GPLv2"
__author__ = "Daniel Armbruster"
__copyright__ = "Copyright (c) 2012 by Daniel Armbruster"
# -----------------------------------------------------------------------------
class Error(Exception):
def __init__(self, line, msg):
self.line = str(line)
self.msg = msg
def display(self):
sys.stderr.write("csbackmail (ERROR): " + self.msg + "\n")
sys.stderr.write("triggered in line: " + self.line + "\n")
class Usage(Error):
def display(self):
usage_text = "Version: "+__version__+"\nLicense: "+__license__+ \
"\n"+__subversion__+"\nAuthor: "+__author__+ """
Usage: csbackmail [-v|--verbose] [-d|--debug] [-l|--logging]
-a|--address ADDRESS [-a|--address ADDRESS [...]]
-s|--sender ADDRESS PATH
or: csbackmail -h|--help\n"""
sys.stderr.write("csbackmail [line "+self.line+"]: "+self.msg+"\n")
# -----------------------------------------------------------------------------
def help():
Printing helptext to stdout.
help_text = "Version: "+__version__+"\nLicense: "+__license__+"\n"+ \
__subversion__+"\nAuthor: "+__author__+"""
Usage: csbackmail [-v|--verbose] [-d|--debug] [-l|--logging]
-r|--receiver ADDRESS [-r|--receiver ADDRESS [...]]
-s|--sender ADDRESS [PATH [PATH [...]]]
or: csbackmail -h|--help
-v|--verbose Be verbose.
-h|--help Display this help.
-d|--debug Debug mode. Be really verbose.
-l|--logging Switch on logging to logfile. Logfile will be located in
-r|--receiver ADDR Email address(es) of the receiver(s). (obligatory)
-s|--sender ADDR Email address of the sender (Sending over SMTP).
PATH Path(s) to the logfile(s) to check.
# -----------------------------------------------------------------------------
def main(argv=None):
# configure logger
logger = csbacklog.CsbackLog('csbackmail')
console = logging.StreamHandler()
console.setFormatter(logging.Formatter( \
'%(name)-8s [%(lineno)d]: %(levelname)-8s %(message)s'))
# fetch arguments
if argv is None:
argv = sys.argv
opts, args = getopt.getopt(argv[1:], "vhdlr:s:", ["help", "verbose", \
"debug", "logging", "receiver=", "sender="])
except getopt.GetoptError as err:
raise Usage(130,err.msg)
verbose = False
debugMode = False
receivers = []
sender = ''
# collect commandline arguments
for opt, arg in opts:
if opt in ("-v", "--verbose"):
verbose = True
elif opt in ("-h", "--help"):
return 0
elif opt in ("-d", "--debug"):
debugMode = True
elif opt in ("-l", "--logging"):
elif opt in ("-r", "--receiver"):
elif opt in ("-s", "--sender"):
sender = arg
raise Usage(144,"Unhandled option chosen.")
if verbose or debugMode:
# fetching and checking arguments
if 1 <= len(args):
logger.getLogger().info("Taking passed PATH(s) as arguments.")
logFilePathes = [str(arg).rstrip(os.sep)+os.sep for arg in args]
# fetch default logfiles
elif 0 == len(args):
logger.getLogger().info("Taking default logfiles in ~/.csback/log/")
logFilePathes = [os.path.join(csbacklog.CsbackLog.logFileDir, logfile) \
for logfile in os.listdir(csbacklog.CsbackLog.logFileDir) \
if None != re.match('csback\.log|csback\.log\.[1-5]', logfile)]
# maybe sort list here
raise Usage(159,"Invalid argument(s).")
logger.getLogger().info("Taking default logfiles in ~/.csback/log/")
if 0 == len(sender):
raise Usage(163, "Email address of sender missing.")
if None == re.match('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$', sender):
raise Error(165, "Email address of sender not valid.")
if 0 == len(receivers):
raise Usage(167, "Email address of receiver missing.")
for add in receivers:
if None == re.match('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$', add):
raise Error(165, "Email address of receiver not valid.")
infoDequeue = dequeue(5)
warningDequeue = dequeue(10)
errorList = []
criticalList = []
# read logfiles
logger.getLogger().info("Reading logfile(s) ...")
for path in logFilePathes:
for line in open(path, 'r+').readlines():
if line.find('INFO'):
elif line.find('WARNING'):
elif line.find('ERROR'):
elif line.find('CRITICAL'):
logger.getLogger().info("Illegal line in logfile found.")
except IOError as err:
raise Error(178, "Error while reading logfiles.")
logger.getLogger().debug("Finished reading logfile(s).")
# prepare email
logger.getLogger().debug("Preparing email content ...")
msg = ' logfile status\n\nNumber of read logfiles: {0}\n\n'\
infoList = list(infoDequeue)
subject = ''
if len(infoList):
subject = 'csback report - severity: INFO'
msg += 'INFO entries (last 5):\n\n'
for line in infoList:
msg += line
warningList = list(warningDequeue)
if len(warningList):
subject = 'csback report - severity: WARNING'
msg += 'WARNING entries (last 10):\n\n'
for line in warningList:
msg += line
if len(errorList):
subject = 'csback report - severity: ERROR'
msg += 'ERROR entries:\n\n'
for line in errorList:
msg += line
if len(criticalList):
subject = 'csback report - severity: CRITICAL'
msg += 'CRITICAL entries:\n\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(receiver[1:])
logger.getLogger().debug("Finished preparation of email content.")
# send mail
logger.getLogger().debug("Sending email.")
s = smtplib.SMTP()
s.sendmail(sender, [receiver[0]], mail.as_string())
except SMTPRecipientsRefused as err:
logger.getLogger().warning( \
"All recipients were refused. Nobody got the mail.")
except SMTPHeloError as err:
logger.getLogger().warning( \
"The server didn’t reply properly to the HELO greeting.")
except SMTPSenderRefused as err:
logger.getLogger().warning( \
"The server didn’t accept the address '%s'", sender)
except SMTPDataError as err:
logger.getLogger().warning( \
"The server replied with an unexpected error code.")
except Usage as err:
return 2
except Error as err:
logger.getLogger().error("message: %s [line %s]", err.msg, err.line)
return 2
logger.getLogger().info("Email sent.")
return 0
# -----------------------------------------------------------------------------
if __name__ == "__main__":
# ----- END OF -----
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