python alternative to grep sort uniq

#!/usr/bin/python
import os
import re
from operator import itemgetter
from collections import defaultdict

count_max=24000
mail_to="mailbox@domain"
mail_subj="spammers"
SENDMAIL = "/usr/sbin/sendmail"
data = defaultdict(int)
notify=False

for line in open('/var/log/mail/mail.log.0','r'):
p = re.compile('pickup.*<(w+)>');
s = p.search(line)
if s:
data[s.group(1)] += 1
if (notify==False and data[s.group(1)]>count_max):
notify=True

if notify==True:
m = os.popen("%s -t" % SENDMAIL, "w")
m.write("To: %sn" % mail_to)
m.write("Subject: %sn" % mail_subj)
m.write("n")
for line, count in sorted(data.iteritems(), key=itemgetter(1), reverse=True):
if count>count_max:
m.write("%7d %sn" % (count, line))
#print "%7d %sn" % (count, line),
m.close()

Leave a Reply

Your email address will not be published. Required fields are marked *