Skip to content

Instantly share code, notes, and snippets.

@svenXY
Last active August 29, 2015 14:19
Show Gist options
  • Save svenXY/61621c318346dd28fb84 to your computer and use it in GitHub Desktop.
Save svenXY/61621c318346dd28fb84 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# encoding: utf-8
'''
Remove Zabbix problem mails if resolved.
This script
- recursively searches a maildir
- looks for mails with PROBLEM in the subject
- Checks if the proper OK subject exists
- if so, deletes both mails
Sven Hergenhahn https://github.com/svenXY
'''
import mailbox
import re
import sys
import email.utils
import time
import logging
import operator
class ZabbixMessage(object):
def __init__(self, subject, date, msgid):
self.subject = subject
self.msgid = msgid
self.date = self.parsetime(date)
pr = re.compile('PROBLEM:')
ok = re.compile('OK:')
if pr.search(self.subject):
self.typ = 'problem'
elif ok.search(subject):
self.typ = 'ok'
else:
logging.info('Strange mail: %s' % self.subject)
def parsetime(self, datestring):
d = email.utils.parsedate(datestring)
return int(time.mktime(d))
def __unicode__(self):
return 'ZabbixMessage: (%d) %s' % (self.date, self.subject)
def sort_messages_by_date(messages):
cmpfun = operator.attrgetter("date")
return messages.sort(key=cmpfun)
def find_problem_msg(messages, subject, date):
for msg in messages:
k = re.sub('PROBLEM', 'OK', msg.subject)
if msg.date < date and subject == k:
logging.debug('Problem message found for (%d) %s' % (date, subject))
return msg
logging.info('No problem message found for (%d) %s' % (date, subject))
if __name__ == '__main__':
logging.basicConfig(
level=logging.WARN,
#filename='/tmp/clean_zabbix_mails.log',
format='%(asctime)s %(message)s',
datefmt='%Y%m%d %H:%M:%S')
try:
mbox = mailbox.Maildir(sys.argv[1])
except IndexError:
logging.fatal('No mailbox specified. Exit.')
print('Usage: %s /path/to/maildir/containing/zabbixmails' % sys.argv[0])
sys.exit(1)
mbox.lock()
messages = []
for key,msg in mbox.iteritems():
messages.append(ZabbixMessage(msg['subject'], msg['date'], key))
sort_messages_by_date(messages)
for msg in messages:
if msg.typ == 'ok':
ids = [ msg.msgid ]
prob = find_problem_msg(messages, msg.subject, msg.date)
try:
if prob:
mbox.discard(prob.msgid)
ids.append(prob.msgid)
mbox.discard(msg.msgid)
messages = [ m for m in messages if m.msgid not in ids]
except KeyError as e:
print('Message not found, thus not deleted: %s' % e)
logging.error('Message not found, thus not deleted: %s' % e)
else:
logging.info('Removed messages: %s' % ', '.join(ids))
mbox.close()
@svenXY
Copy link
Author

svenXY commented Apr 15, 2015

The latest version sorts the list of messages by date first, compares the timestamps (verifies that the PROBLEM-mail is older) and will only ever delete on PROBLEM-mail per OK-mail.

Some logging has been added as well

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment