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

added SMTP relevant flags

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:
SVN Revision: 4344
SVN UUID:     67feda4a-a26e-11df-9d6e-31afc202ad0c
parent 956ea11f
......@@ -73,9 +73,10 @@ 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
Usage: csbackmail [-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")
......@@ -87,9 +88,10 @@ def help():
help_text = "Version: "+__version__+"\nLicense: "+__license__+"\n"+ \
__subversion__+"\nAuthor: "+__author__+"""
Usage: csbackmail [-v|--verbose] [-d|--debug] [-l|--logging]
Usage: csbackmail [-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 [...]]]
-s|--sender ADDRESS [PATH [PATH [...]]]
or: csbackmail -h|--help
-v|--verbose Be verbose.
......@@ -98,8 +100,12 @@ def help():
-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).
-s|--sender ADDR Email address of the sender (Sending over SMTP).
-P|--port ARG SMTP port.
-H|--host ARG Hostname of the SMTP server.
-u|--username ARG Username for SMTP server login.
-p|--password ARG Password for SMTP server login.
PATH Path(s) to the logfile(s) to check.
......@@ -118,14 +124,19 @@ def main(argv=None):
argv = sys.argv
opts, args = getopt.getopt(argv[1:], "vhdlr:s:", ["help", "verbose", \
"debug", "logging", "receiver=", "sender="])
opts, args = getopt.getopt(argv[1:], "vhdlr:s:P:H:u:p:", ["help", \
"verbose", "debug", "logging", "receiver=", "sender=", "port=", \
"host=", "username=", "password="])
except getopt.GetoptError as err:
raise Usage(130,err.msg)
verbose = False
debugMode = False
receivers = []
sender = ''
port = int()
host = ''
username = ''
password = ''
# collect commandline arguments
for opt, arg in opts:
if opt in ("-v", "--verbose"):
......@@ -143,8 +154,16 @@ def main(argv=None):
elif opt in ("-s", "--sender"):
sender = arg
elif opt in ("-P", "--port"):
port = int(arg)
elif opt in ("-H", "--host"):
host = arg
elif opt in ("-u", "--username"):
username = arg
elif opt in ("-p", "--password"):
password = arg
raise Usage(144,"Unhandled option chosen.")
raise Usage(166,"Unhandled option chosen.")
if verbose or debugMode:
......@@ -159,25 +178,27 @@ def main(argv=None):
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).")
raise Usage(183,"Invalid argument(s).")
logger.getLogger().info("Taking default logfiles in ~/.csback/log/")
logger.getLogger().debug("Checking email addresses.")
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.")
raise Usage(189, "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(192, "Email address of sender not valid.")
if 0 == len(receivers):
raise Usage(167, "Email address of receiver missing.")
raise Usage(194, "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.")
if None == re.match( \
'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$', add):
raise Error(198, "Email address of receiver not valid.")
infoDequeue = dequeue(5)
warningDequeue = dequeue(10)
infoDequeue = deque(maxlen=5)
warningDequeue = deque(maxlen=10)
errorList = []
criticalList = []
# read logfiles
......@@ -196,34 +217,50 @@ def main(argv=None):
logger.getLogger().info("Illegal line in logfile found.")
except IOError as err:
raise Error(178, "Error while reading logfiles.")
raise Error(220, "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'\
logger.getLogger().info("Preparing email content ...")
msg = '============================\n'
msg += ' logfile status\n'
msg += '============================\n'
msg += 'Number of read logfiles: {0}\n\n'.format(len(logFilePathes))
infoList = list(infoDequeue)
subject = ''
if len(infoList):
logger.getLogger().debug("Adding INFO logfile lines to mail content.")
subject = 'csback report - severity: INFO'
msg += 'INFO entries (last 5):\n\n'
msg += '--------------------------\n'
msg += 'INFO entries (last 5):\n'
msg += '--------------------------\n'
for line in infoList:
msg += line
warningList = list(warningDequeue)
if len(warningList):
logger.getLogger().debug( \
"Adding WARNING logfile lines to mail content.")
subject = 'csback report - severity: WARNING'
msg += 'WARNING entries (last 10):\n\n'
msg += '--------------------------\n'
msg += 'WARNING entries (last 10):\n'
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 += 'ERROR entries:\n\n'
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 += 'CRITICAL entries:\n\n'
msg += '--------------------------\n'
msg += 'CRITICAL entries:\n'
msg += '--------------------------\n'
for line in criticalList:
msg += line
......@@ -237,27 +274,29 @@ def main(argv=None):
# send mail
logger.getLogger().debug("Sending email.")
s = smtplib.SMTP()
s.sendmail(sender, [receiver[0]], mail.as_string())
except SMTPRecipientsRefused as err:
session = smtplib.SMTP(host=host, port=port)
session.login(username, password)
session.sendmail(sender, receivers, mail.as_string())
except smtplib.SMTPRecipientsRefused:
logger.getLogger().warning( \
"All recipients were refused. Nobody got the mail.")
except SMTPHeloError as err:
except smtplib.SMTPHeloError:
logger.getLogger().warning( \
"The server didn’t reply properly to the HELO greeting.")
except SMTPSenderRefused as err:
except smtplib.SMTPSenderRefused:
logger.getLogger().warning( \
"The server didn’t accept the address '%s'", sender)
except SMTPDataError as err:
except smtplib.SMTPDataError:
logger.getLogger().warning( \
"The server replied with an unexpected error code.")
except Usage as err:
......@@ -269,8 +308,6 @@ def main(argv=None):
logger.getLogger().info("Email sent.")
return 0
# -----------------------------------------------------------------------------
if __name__ == "__main__":
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