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

Here you are Thomas :-) - providing status output to stdout

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: 4702
SVN UUID:     67feda4a-a26e-11df-9d6e-31afc202ad0c
parent 89858e88
......@@ -34,6 +34,7 @@
# REVISIONS and CHANGES
# 05/01/2012 V0.1 Daniel Armbruster
# 12/01/2012 V0.2 provide nagios status line
# 10/05/2012 V0.3 provide output to stdout
#
# =============================================================================
"""
......@@ -51,7 +52,7 @@ import csbacklog
from email.mime.text import MIMEText
from collections import deque
__version__ = "V0.2"
__version__ = "V0.3"
__subversion__ = "$Id$"
__license__ = "GPLv2"
__author__ = "Daniel Armbruster"
......@@ -80,6 +81,8 @@ class Usage(Error):
-s|--sender ADDRESS [PATH [PATH [...]]]
or: csbackntfy [-v|--verbose] [-d|--debug] [-l|--logging] -n|--nagios
[PATH [PATH [...]]]
or: csbackntfy [-v|--verbose] [-d|--debug] [-l|--logging] -o|--out
[PATH [PATH [...]]]
or: csbackntfy -h|--help\n"""
sys.stderr.write("csbackntfy [line "+self.line+"]: "+self.msg+"\n")
sys.stderr.write(usage_text)
......@@ -97,6 +100,8 @@ def help():
-s|--sender ADDRESS [PATH [PATH [...]]]
or: csbackntfy [-v|--verbose] [-d|--debug] [-l|--logging] -n|--nagios
[PATH [PATH [...]]]
or: csbackntfy [-v|--verbose] [-d|--debug] [-l|--logging] -o|--out
[PATH [PATH [...]]]
or: csbackntfy -h|--help
-------------------------------------------------------------------------------
-v|--verbose Be verbose.
......@@ -114,6 +119,7 @@ def help():
-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.
-o|--out Send output to stdout instead of sending an email.
PATH Path(s) of the logfile(s) to check. If not specified the
logfiles in /var/log/ were investigated.
"""
......@@ -133,9 +139,9 @@ def main(argv=None):
argv = sys.argv
try:
try:
opts, args = getopt.getopt(argv[1:], "vhdlr:s:P:H:u:p:nt", ["help", \
opts, args = getopt.getopt(argv[1:], "vhdlr:s:P:H:u:p:nto", ["help", \
"verbose", "debug", "logging", "receiver=", "sender=", "port=", \
"host=", "username=", "password=", '--nagios', '--tls'])
"host=", "username=", "password=", 'nagios', 'tls', 'out'])
except getopt.GetoptError as err:
raise Usage(139,err.msg)
verbose = False
......@@ -148,6 +154,8 @@ def main(argv=None):
password = ''
nagiosMode = False
useTLS = False
stdoutMode = False
# collect commandline arguments
for opt, arg in opts:
if opt in ("-v", "--verbose"):
......@@ -177,6 +185,8 @@ def main(argv=None):
nagiosMode = True
elif opt in ("-t", "--tls"):
useTLS = True
elif opt in ("-o", "--out"):
stdoutMode = True
else:
raise Usage(177,"Unhandled option chosen.")
......@@ -233,31 +243,32 @@ def main(argv=None):
sys.stdout.write("CSBACK WARNING\n")
else:
sys.stdout.write("CSBACK OK\n")
# generate the email using pythons smtplib
# generate the email using pythons smtplib or write to stdout
else:
logger.getLogger().debug("Checking email addresses.")
if 0 == len(sender):
raise Usage(236, "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(239, "Email address of sender not valid.")
if 0 == len(receivers):
raise Usage(241, "Email address of receiver missing.")
for add in receivers:
if not stdoutMode:
logger.getLogger().debug("Checking email addresses.")
if 0 == len(sender):
raise Usage(236, "Email address of sender missing.")
if None == re.match( \
'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$', add):
raise Error(245, "Email address of receiver not valid.")
'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$', sender):
raise Error(239, "Email address of sender not valid.")
if 0 == len(receivers):
raise Usage(241, "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(245, "Email address of receiver not valid.")
if 0 == len(host):
raise Usage(248, "Hostname missing.")
if 0 == len(username):
raise Usage(250, "Username missing.")
if 0 == len(password):
raise Usage(252, "Password missing.")
if -1 == port:
raise Usage(254, "Port missing.")
if 0 == len(host):
raise Usage(248, "Hostname missing.")
if 0 == len(username):
raise Usage(250, "Username missing.")
if 0 == len(password):
raise Usage(252, "Password missing.")
if -1 == port:
raise Usage(254, "Port missing.")
# prepare email
logger.getLogger().debug("Preparing email content ...")
logger.getLogger().debug("Preparing content ...")
msg = '============================\n'
msg += 'csbackntfy.py logfile status\n'
msg += '============================\n'
......@@ -265,7 +276,7 @@ def main(argv=None):
infoList = list(infoDeque)
subject = ''
if len(infoList):
logger.getLogger().debug("Adding INFO logfile lines to mail content.")
logger.getLogger().debug("Adding INFO logfile lines to content.")
subject = 'csback report - severity: INFO'
msg += '--------------------------\n'
msg += 'INFO entries (last {0}):\n'.format(len(infoList))
......@@ -275,7 +286,7 @@ def main(argv=None):
warningList = list(warningDeque)
if len(warningList):
logger.getLogger().debug( \
"Adding WARNING logfile lines to mail content.")
"Adding WARNING logfile lines to content.")
subject = 'csback report - severity: WARNING'
msg += '--------------------------\n'
msg += 'WARNING entries (last {0}):\n'.format(len(warningList))
......@@ -283,7 +294,7 @@ def main(argv=None):
for line in warningList:
msg += line
if len(errorList):
logger.getLogger().debug("Adding ERROR logfile lines to mail content.")
logger.getLogger().debug("Adding ERROR logfile lines to content.")
subject = 'csback report - severity: ERROR'
msg += '--------------------------\n'
msg += 'ERROR entries:\n'
......@@ -292,50 +303,55 @@ def main(argv=None):
msg += line
if len(criticalList):
logger.getLogger().debug( \
"Adding CRITICAL logfile lines to mail content.")
"Adding CRITICAL logfile lines to 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 stdoutMode:
# write output to stdout
sys.stdout.write('Subject: '+subject+'\n\n')
sys.stdout.write(msg+'\n')
else:
# send mail
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.ehlo()
if useTLS:
session.starttls()
logger.getLogger().debug("Sending email.")
try:
session = smtplib.SMTP(host=host, port=port)
session.ehlo()
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 useTLS:
session.starttls()
session.ehlo()
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()
......@@ -345,7 +361,7 @@ def main(argv=None):
err.display()
return 2
else:
if not nagiosMode:
if not nagiosMode and not stdoutMode:
logger.getLogger().info("Email sent.")
return 0
......
Supports Markdown
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