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:     http://gpitrsvn.gpi.uni-karlsruhe.de/repos/TFSoftware/trunk
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")
sys.stderr.write(usage_text)
......@@ -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
~/.csback/log/.
-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).
(obligatory)
-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.
"""
sys.stdout.write(help_text)
......@@ -118,14 +124,19 @@ def main(argv=None):
argv = sys.argv
try:
try:
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):
receivers.append(arg)
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
else:
raise Usage(144,"Unhandled option chosen.")
raise Usage(166,"Unhandled option chosen.")
if verbose or debugMode:
logger.addHandler(console)
......@@ -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
logFilePathes.reverse()
else:
raise Usage(159,"Invalid argument(s).")
raise Usage(183,"Invalid argument(s).")
print(logFilePathes)
print(logFilePathes)
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):
else:
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 = 'csbackmail.py logfile status\n\nNumber of read logfiles: {0}\n\n'\
.format(len(logFilePathes))
logger.getLogger().info("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(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()
try:
s.sendmail(sender, [receiver[0]], mail.as_string())
except SMTPRecipientsRefused as err:
s.quit()
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 SMTPHeloError as err:
s.quit()
except smtplib.SMTPHeloError:
session.quit()
logger.getLogger().warning( \
"The server didn’t reply properly to the HELO greeting.")
except SMTPSenderRefused as err:
s.quit()
except smtplib.SMTPSenderRefused:
session.quit()
logger.getLogger().warning( \
"The server didn’t accept the address '%s'", sender)
except SMTPDataError as err:
except smtplib.SMTPDataError:
session.quit()
logger.getLogger().warning( \
"The server replied with an unexpected error code.")
s.quit()
else:
s.quit()
session.quit()
except Usage as err:
err.display()
......@@ -269,8 +308,6 @@ def main(argv=None):
else:
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