Last active
October 17, 2019 20:11
-
-
Save athoune/91b1e57df2e347add5d48e38e31ae1aa to your computer and use it in GitHub Desktop.
Parsing mailq format (from Postfix 2.x)
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
#!/usr/bin/env python3 | |
import subprocess | |
import re | |
from pypred import Predicate | |
SPACE = re.compile(r"\s+") | |
def mailq(): | |
mq = subprocess.Popen(['mailq'], stdout=subprocess.PIPE) | |
buffer = [] | |
prems = True | |
for line in mq.stdout: | |
if prems: | |
prems = False | |
continue | |
buffer.append(line[:-1]) | |
if line == b'\n': | |
# Each entry shows the queue file ID, message size, arrival time, sender, and the recipients that still need to be delivered. | |
meta = SPACE.split(buffer[0].decode("utf8")) | |
id = meta[0] | |
size = int(meta[1]) | |
sender = meta[-1] | |
date = " ".join(meta[2:-1]) | |
dest = buffer[2].decode('utf8').strip() | |
# FIXME sometime, there is more than one dest | |
yield id, size, date, sender, buffer[1].decode('utf8'), dest | |
buffer = [] | |
def main(): | |
import sys | |
if len(sys.argv) == 2: | |
p = Predicate(sys.argv[1]) | |
if not p.is_valid(): | |
for error in p.errors()['errors']: | |
print(error) | |
return | |
else: | |
p = None | |
for id, size, date, sender, msg, dest in mailq(): | |
doc = dict(id=id, size=size, date=date, sender=sender, msg=msg, dest=dest) | |
if p == None or p.evaluate(doc): | |
print(doc) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment