#!/usr/bin/env python import sys,os,re #Option handling nice and easy through Optik, http://optik.sf.net from optik import OptionParser parser = OptionParser() parser.add_option ("-d", "--queue-dir",action="store", type="string", dest="queuedir", help="The qmail queue directory, default=/var/qmail/queue", default="/var/qmail/queue") parser.add_option ("-s", "--sender",action="store", type="string", dest="sender", help="Find messages with a From: header matching this regexp", default=None) parser.add_option ("-t", "--to",action="store", type="string", dest="to", help="Find messages with a To: header matching this regexp", default=None) parser.add_option ("--header",action="store", type="string", dest="header", help="Find messages with any header matching this regexp", default=None) parser.add_option("-v", action="store_true", dest="verbose", help="Verbose",default=0) parser.add_option("-q", action="store_false", dest="verbose", help="Quiet") (options,args) = parser.parse_args (sys.argv) #This is where the messages are msgdir=options.queuedir+"/mess" #Array of matching messages matches=[] #Create the regexp to be matched regex="" if options.header: #User gave us a full regexp regex=options.header elif options.sender: #User asks for a From: header regex="^From: "+options.sender elif options.to: #User asks for a To: header regex="^To: "+options.to exp=re.compile(regex) if options.verbose: print "Searching messages with headers matching: %s\n"%regex #Function that checks if a message matches our criteria def check(message): global exp,matches for line in open(message): #Only check the headers, so stop on blank line if len(line)==1: return #Check for match if exp.search(line,1): matches.append(message.split("/")[-1]) return #Get list of split directories (usually they are 23, but why bet) try: dirs=os.listdir(msgdir) except: sys.stdout.write("Error listing queue directories") sys.exit(1) #Walk the tree and examine each file for dir in dirs: files=os.listdir(msgdir+"/"+dir) for file in files: check (msgdir+"/"+dir+"/"+file) #report files matching our criterion for match in matches: print match