Advertisement
Guest User

check

a guest
Dec 13th, 2017
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.55 KB | None | 0 0
  1. #!/usr/bin/env python
  2. __title__ = "check_emails"
  3. __version__ = "1.0.0"
  4.  
  5. import os
  6. import sys
  7. import signal
  8. import imaplib
  9. import re
  10. #import argparse
  11. #import ConfigParser
  12.  
  13.  
  14. #import dateutil.parser
  15. #from datetime import datetime
  16. #import pytz
  17.  
  18. #OLD_PYTHON = False
  19. #try:
  20. #   from subprocess import Popen, PIPE, STDOUT
  21. #except ImportError:
  22. #   OLD_PYTHON = True
  23. #   import commands
  24. #from optparse import OptionParser
  25.  
  26.  
  27. EXIT_OK = 0
  28. EXIT_WARNING = 1
  29. EXIT_CRITICAL = 2
  30. EXIT_UNKNOWN = 3
  31.  
  32. DEFAULT_PORT = 993
  33. DEFAULT_PROFILECONFIG = '/etc/nagios-plugins/check_email_delivery_credentials.ini'
  34. DEFAULT_WARN = 120
  35. DEFAULT_CRIT = 600
  36.  
  37. parser = argparse.ArgumentParser(description='This program checks if the most recent mail in an IMAP inbox is not older than a certain time. Use this check as a companion to check_smtp_send.py, which sends test email messages.')
  38. parser.add_argument('-H', dest='host', metavar='host', required=True, help='SMTP host')
  39. parser.add_argument('--port', type=int, default=DEFAULT_PORT, help='SMTP port (default=%i)'%DEFAULT_PORT)
  40. parser.add_argument('--profile', required=True, help='credential profile in config file')
  41. parser.add_argument('--profileconfig', metavar='config.ini', default=DEFAULT_PROFILECONFIG, help='location of the config file (default=%s)'%DEFAULT_PROFILECONFIG)
  42. parser.add_argument('-w', type=int, metavar='warningseconds', dest='warn', default=DEFAULT_WARN, help='warn, if the most recent message is older than this value (default=%s)' % DEFAULT_WARN)
  43. parser.add_argument('-c', type=int, metavar='criticalseconds', dest='crit', default=DEFAULT_CRIT, help='critical, if the most recent message is older than this value (default=%s)' % DEFAULT_CRIT)
  44.  
  45. try:
  46.     args = vars(parser.parse_args())
  47. except SystemExit:
  48.     sys.exit(EXIT_UNKNOWN)
  49.  
  50. host = args['host']
  51. port = args['port']
  52. profile = args['profile']
  53. profileconfig = args['profileconfig']
  54. warn = args['warn']
  55. crit = args['crit']
  56.  
  57. config = ConfigParser.SafeConfigParser()
  58. config.read(profileconfig)
  59.  
  60. try:
  61.     username = config.get(profile,'username')
  62.     password = config.get(profile,'password')
  63. except ConfigParser.NoSectionError:
  64.     print('Configuration error: profile %s does not exist' % profile)
  65.     sys.exit(EXIT_UNKNOWN)
  66. except ConfigParser.NoOptionError:
  67.     print('Configuration error: profile %s does not contain username or password' % profile)
  68.     sys.exit(EXIT_UNKNOWN)
  69. try:
  70.     imap = imaplib.IMAP4_SSL(host, port)
  71.     imap.login(username, password)
  72.     imap.select()
  73.     typ, data = imap.search(None, 'ALL')
  74.  
  75.     pattern = re.compile(r'\(INTERNALDATE "(.+)"\)')
  76.  
  77.     messages = []
  78.     for num in data[0].split():
  79.         typ, data = imap.fetch(num, '(INTERNALDATE)')
  80.         if typ != 'OK':
  81.             # TODO: error handling
  82.             sys.exit(EXIT_UNKNOWN)
  83.         m = pattern.search(data[0])
  84.         d = dateutil.parser.parse(m.group(1))
  85.         messages.append((d,num))
  86.  
  87.     sortedmessages = sorted(messages, key=lambda x: x[0])
  88.  
  89.     mostrecent = sortedmessages[-1]
  90.     for d,num in sortedmessages[:-1]:
  91.         imap.store(num, '+FLAGS', '\\Deleted')
  92.  
  93.     imap.expunge()
  94.     imap.close()
  95.     imap.logout()
  96. except IMAP4.abort as e:
  97.     # IMAP4 server errors cause this exception to be raised. This is a sub-class of IMAP4.error. Note that closing the instance and instantiating a new one will usually allow recovery from this exception.
  98.     print e
  99.     sys.exit(EXIT_CRITICAL)
  100. except IMAP4.readonly as e:
  101.     # This exception is raised when a writable mailbox has its status changed by the server. This is a sub-class of IMAP4.error. Some other client now has write permission, and the mailbox will need to be re-opened to re-obtain write permission.
  102.     print e
  103.     sys.exit(EXIT_CRITICAL)
  104. except IMAP4.error as e:
  105.     # Exception raised on any errors. The reason for the exception is passed to the constructor as a string.
  106.     print e
  107.     sys.exit(EXIT_CRITICAL)
  108.  
  109. sec = (datetime.now(pytz.utc) - mostrecent[0]).total_seconds()
  110.  
  111. def end(status, message, perfdata=""):
  112.     """Exits the plugin with first arg as the return code and the second arg as the message to output."""
  113.  
  114.     if perfdata:
  115.         print "%s | %s" % (message, perfdata)
  116.     else:
  117.         print "%s" % message
  118.  
  119.     if status == OK:
  120.         sys.exit(OK)
  121.     elif status == WARNING:
  122.         sys.exit(WARNING)
  123.     elif status == CRITICAL:
  124.         sys.exit(CRITICAL)
  125.     else:
  126.         sys.exit(UNKNOWN)
  127.  
  128.  
  129.  
  130. #def print_message(status):
  131. #     print "%s|mostrecent=%i;%i;%i;0;" % (status, sec, warn, crit)
  132.  
  133. #if sec > crit:
  134. #    print_message('CRITICAL')
  135. #    sys.exit(EXIT_CRITICAL)
  136. #elif sec > warn:
  137. #    print_message('WARNING')
  138. #    sys.exit(EXIT_WARNING)
  139.  
  140. #print_message('OK')
  141. #sys.exit(EXIT_OK)
  142.  
  143.  
  144. #!/usr/bin/env python
  145.  
  146. __title__ = "check_emails"
  147. __version__ = "1.0.0"
  148.  
  149.  
  150. import os
  151. import sys
  152. import datetime
  153. import time
  154. import uuid
  155. import signal
  156. import imaplib
  157. import re
  158. import dateutil.parser
  159. from datetime import datetime
  160. import pytz
  161. import argparse
  162. import ConfigParser
  163. import smtplib
  164. from email.mime.text import MIMEText
  165. from email import utils
  166.  
  167.  
  168. OLD_PYTHON = False
  169. try:
  170.     from subprocess import Popen, PIPE, STDOUT
  171. except ImportError:
  172.     OLD_PYTHON = True
  173.     import commands
  174. from optparse import OptionParser
  175.  
  176. EXIT_OK = 0
  177. EXIT_WARNING = 1
  178. EXIT_CRITICAL = 2
  179. EXIT_UNKNOWN = 3
  180.  
  181. DEFAULT_PORT = 587
  182. DEFAULT_PROFILECONFIG = '/etc/nagios-plugins/check_email_delivery_credentials.ini'
  183.  
  184. parser = argparse.ArgumentParser(description='This program sends a test email message over SMTP TLS.')
  185. parser.add_argument('-H', dest='host', metavar='host', required=True, help='SMTP host')
  186. parser.add_argument('--port', type=int, default=DEFAULT_PORT, help='SMTP port (default=%i)'%DEFAULT_PORT)
  187. parser.add_argument('--profile', required=True, help='credential profile in config file')
  188. parser.add_argument('--profileconfig', metavar='config.ini', default=DEFAULT_PROFILECONFIG, help='location of the config file (default=%s)'%DEFAULT_PROFILECONFIG)
  189. parser.add_argument('--mailfrom', metavar='sender@host1', required=True, help='email address of the test message sender')
  190. parser.add_argument('--mailto', metavar='receiver@host2', required=True, help='email address of the test message receiver')
  191.  
  192. try:
  193.     args = vars(parser.parse_args())
  194. except SystemExit:
  195.     sys.exit(EXIT_UNKNOWN)
  196.  
  197. host = args['host']
  198. port = args['port']
  199. profile = args['profile']
  200. profileconfig = args['profileconfig']
  201. mailfrom = args['mailfrom']
  202. mailto = args['mailto']
  203.  
  204. config = ConfigParser.SafeConfigParser()
  205. config.read(profileconfig)
  206.  
  207. try:
  208.     username = config.get(profile,'username')
  209.     password = config.get(profile,'password')
  210. except ConfigParser.NoSectionError:
  211.     print('Configuration error: profile %s does not exist' % profile)
  212.     sys.exit(EXIT_UNKNOWN)
  213. except ConfigParser.NoOptionError:
  214.     print('Configuration error: profile %s does not contain username or password' % profile)
  215.     sys.exit(EXIT_UNKNOWN)
  216.  
  217. #msg = MIMEText('This is a test message by the monitoring system to check if email delivery is running fine.')
  218. #msg['Subject'] = 'TEST'
  219. #msg['From'] = mailfrom
  220. #msg['To'] = mailto
  221. #msg['Message-ID'] = '<' + str(uuid.uuid4()) + '@' + host + '>'
  222.  
  223. #nowdt = datetime.datetime.now()
  224. #nowtuple = nowdt.timetuple()
  225. #nowtimestamp = time.mktime(nowtuple)
  226.  
  227. #msg['Date'] = utils.formatdate(nowtimestamp)
  228.  
  229. try:
  230.     smtp = smtplib.SMTP(host, port)
  231.     smtp.starttls()
  232.     smtp.login(username, password)
  233.     smtp.sendmail(mailfrom, mailto, msg.as_string())
  234. except smtplib.SMTPServerDisconnected as e:
  235.     # This exception is raised when the server unexpectedly disconnects, or when an attempt is made to use the SMTP instance before connecting it to a server.
  236.     print e
  237.     sys.exit(EXIT_CRITICAL)
  238. except smtplib.SMTPResponseException as e:
  239.     # Base class for all exceptions that include an SMTP error code. These exceptions are generated in some instances when the SMTP server returns an error code. The error code is stored in the smtp_code attribute of the error, and the smtp_error attribute is set to the error message.
  240.     print e
  241.     sys.exit(EXIT_CRITICAL)
  242. except smtplib.SMTPSenderRefused as e:
  243.     # Sender address refused. In addition to the attributes set by on all SMTPResponseException exceptions, this sets 'sender' to the string that the SMTP server refused.
  244.     print e
  245.     sys.exit(EXIT_CRITICAL)
  246. except smtplib.SMTPRecipientsRefused as e:
  247.     # All recipient addresses refused. The errors for each recipient are accessible through the attribute recipients, which is a dictionary of exactly the same sort as SMTP.sendmail() returns.
  248.     print e
  249.     sys.exit(EXIT_CRITICAL)
  250. except smtplib.SMTPDataError as e:
  251.     # The SMTP server refused to accept the message data.
  252.     print e
  253.     sys.exit(EXIT_CRITICAL)
  254. except smtplib.SMTPConnectError as e:
  255.     # Error occurred during establishment of a connection with the server.
  256.     print e
  257.     sys.exit(EXIT_CRITICAL)
  258. except smtplib.SMTPHeloError as e:
  259.     # The server refused our HELO message.
  260.     print e
  261.     sys.exit(EXIT_CRITICAL)
  262. except smtplib.SMTPAuthenticationError as e:
  263.     # SMTP authentication went wrong. Most probably the server didn't accept the username/password combination provided.
  264.     print e
  265.     sys.exit(EXIT_CRITICAL)
  266. except smtplib.SMTPException as e:
  267.     # The base exception class for all the other exceptions provided by this module.
  268.     print e
  269.     sys.exit(EXIT_CRITICAL)
  270.  
  271. print('OK')
  272. sys.exit(EXIT_OK)
  273.  
  274.  
  275. [profile1]
  276. username=account1
  277. password=somepassword
  278.  
  279. [profile2]
  280. username=account2
  281. password=someotherpassword
  282.  
  283. [profile3]
  284. username=account3
  285. password=someotherpassword
  286.  
  287. [profile4]
  288. username=account4
  289. password=someotherpassword
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement