Last active
August 29, 2015 13:57
-
-
Save FRII/9748818 to your computer and use it in GitHub Desktop.
Mail delivery time (nagios check)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import optparse | |
import json | |
import smtplib | |
import sys | |
import time | |
import email.utils | |
import random | |
import string | |
import os.path | |
import os | |
import traceback | |
from socket import gethostname | |
from email.mime.text import MIMEText | |
from email import message_from_file | |
CONFIGFILE = "/path/to/config.json" | |
if __name__ == "__main__": | |
try: | |
parser = optparse.OptionParser(usage="Usage: %prog [options]") | |
parser.add_option("--config", dest="config", type="str", help="Config file path", default="") | |
parser.add_option("-w", "--warning", dest="warning", type="float", help="Delivery time before warning") | |
parser.add_option("-c", "--critical", dest="critical", type="float", help="Delivery time before critical") | |
options, args = parser.parse_args() | |
global CONFIG | |
CONFIG = None | |
if options.config != "": | |
with open(options.config) as f: | |
CONFIG = json.load(f) | |
else: | |
with open(CONFIGFILE) as f: | |
CONFIG = json.load(f) | |
hostname = gethostname() + "." + CONFIG["domain"] | |
if options.warning > options.critical: | |
raise Exception("Warning time cannot be greater than critical time.") | |
times = [] | |
for root, dirs, files in os.walk(os.path.join(CONFIG["maildir"], "Maildir", "new")): | |
for name in files: | |
filename = os.path.join(root, name) | |
stats = os.stat(filename) | |
with open(filename) as emailf: | |
msg = message_from_file(emailf) | |
if msg["Subject"].lower().strip() == hostname.lower().strip(): | |
body = msg.get_payload() | |
starttime = float(body.strip()) | |
times.append((starttime, stats.st_ctime)) | |
os.remove(filename) | |
if len(times) == 0: | |
print "No messages found." | |
sys.exit(3) | |
times.sort(key=lambda t: t[0]) | |
latest = times[-1] | |
start = latest[0] | |
end = latest[1] | |
deliverytime = end - start | |
print "Delivery time: %s" % deliverytime | |
if deliverytime > options.critical: | |
sys.exit(2) | |
elif deliverytime > options.warning: | |
sys.exit(1) | |
else: | |
sys.exit(0) | |
except Exception, e: | |
traceback.print_exc() | |
print str(e) | |
sys.exit(3) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"servers" : ["smtp01.example.com", "smtp02.example.com"], | |
"domain" : "example.com", | |
"smtp_user" : "deliverytimer@example.com", | |
"smtp_pass" : "tOtAlLySeCuRePaSsWoRd!1", | |
"from_header" : "deliverytimer@example.com", | |
"to_header" : "deliverytimer@example.com", | |
"mail_from" : "deliverytimer@example.com", | |
"rcpt_to" : "deliverytimer@example.com", | |
"maildir" : "/path/to/maildir" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import optparse | |
import json | |
import smtplib | |
import sys | |
import time | |
import email.utils | |
import random | |
import string | |
from email.mime.text import MIMEText | |
CONFIGFILE = "/path/to/config.json" | |
def debugwrite(s): | |
if DEBUG: | |
sys.stderr.write(s) | |
def dumpRecipientsRefused(e): | |
'''Takes in an SMTPRecipientsRefused exception and | |
pretty prints it if verbosity is set.''' | |
if DEBUG: | |
sys.stderr.write("Recipient Address Refused.\n") | |
for k, v in e.recipients.items(): | |
sys.stderr.write("%s: %s (%s)\n" % (k, v[0], v[1])) | |
def sendMessage(smtp, messagestr, env_from_address, sendingtoaddress): | |
'''Sends the given message to the given address, | |
using the given SMTP instance.''' | |
debugwrite("Sending a message.\n") | |
try: | |
smtp.sendmail(env_from_address, | |
sendingtoaddress, | |
messagestr) | |
except smtplib.SMTPRecipientsRefused, e: | |
dumpRecipientsRefused(e) | |
except smtplib.SMTPHeloError, e: | |
debugwrite("SMTP server failed to respond correctly to HELO command.\n", 1) | |
except smtplib.SMTPSenderRefused, e: | |
debugwrite( | |
"SMTP server rejected env-from address of %s.\n" | |
% env_from_address, 1) | |
except smtplib.SMTPDataError, e: | |
debugwrite("Unknown STMP error.\n") | |
if __name__=="__main__": | |
parser = optparse.OptionParser(usage="Usage: %prog [options] server") | |
parser.add_option("--config", dest="config", type="str", help="Config file path", default="") | |
parser.add_option("-d", "--debug", dest="debug", action="store_true", help="Debugging output.", default=False) | |
options, args = parser.parse_args() | |
global DEBUG | |
DEBUG = options.debug | |
global CONFIG | |
if options.config != "": | |
with open(options.config) as f: | |
CONFIG = json.load(f) | |
else: | |
with open(CONFIGFILE) as f: | |
CONFIG = json.load(f) | |
for server in CONFIG["servers"]: | |
smtp = smtplib.SMTP(server) | |
if "smtp_user" in CONFIG and "smtp_pass" in CONFIG: | |
smtp.login(CONFIG["smtp_user"], CONFIG["smtp_pass"]) | |
messageraw = str(time.time()) | |
message = MIMEText(messageraw) | |
message["Date"] = email.utils.formatdate() | |
message["From"] = CONFIG["from_header"] | |
message["To"] = CONFIG["to_header"] | |
message["Subject"] = server | |
sendMessage(smtp, message.as_string(), CONFIG["mail_from"], CONFIG["rcpt_to"]) | |
smtp.close() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment