fork download
  1. import re
  2.  
  3. string = """
  4. msg=audit(1234902.147:88): pid=254 uid=1000 auid=1000 ses=3 subj=random_ex:random_ex:random_ex:d3-d3:w0.c12 30 msg='op=PAM:accounting grantors=pam_unix,pam_localuser acct="lemoney" exe="/usr/bin/grep" hostname=? a ddr=? terminal=/dev/pts/0 res=success'
  5.  
  6. msg=audit(432787023.324:77): pid=1254 uid=1000 auid=1000 ses=3 subj=random_ex:random_ex:random_ex:d3-d3:w0.c12 30 msg='op=PAM:accounting grantors=pam_unix,pam_localuser acct="lemoney" exe="/usr/bin/tail" hostname=? a ddr=? terminal=/dev/pts/0 res=success'
  7. """
  8.  
  9. # lines regex
  10. entries = re.compile(r'^msg=.+', re.MULTILINE)
  11.  
  12. # outer regex
  13. rx = re.compile("""
  14. ((\w+)='([^']+)') # longer group
  15. | # or
  16. (\w+=\S+) # single items
  17. """, re.VERBOSE)
  18.  
  19. # inner regex
  20. ry = re.compile("(\w+)=(\S+)")
  21.  
  22. for entry in entries.finditer(string):
  23. result = dict()
  24. for match in rx.finditer(entry.group(0)):
  25. try:
  26. key, value = match.group(4).split('=')
  27. result[key] = value
  28. except:
  29. #key = match.group(2)
  30.  
  31. inner = dict()
  32. for m in ry.finditer(match.group(3)):
  33. inner[m.group(1)] = m.group(2)
  34.  
  35. result["mess"] = inner
  36.  
  37. print(result)
Success #stdin #stdout 0.01s 9992KB
stdin
Standard input is empty
stdout
{'auid': '1000', 'ses': '3', 'msg': 'audit(1234902.147:88):', 'pid': '254', 'mess': {'exe': '"/usr/bin/grep"', 'terminal': '/dev/pts/0', 'ddr': '?', 'res': 'success', 'acct': '"lemoney"', 'hostname': '?', 'grantors': 'pam_unix,pam_localuser', 'op': 'PAM:accounting'}, 'uid': '1000', 'subj': 'random_ex:random_ex:random_ex:d3-d3:w0.c12'}
{'auid': '1000', 'ses': '3', 'msg': 'audit(432787023.324:77):', 'pid': '1254', 'mess': {'exe': '"/usr/bin/tail"', 'terminal': '/dev/pts/0', 'ddr': '?', 'res': 'success', 'acct': '"lemoney"', 'hostname': '?', 'grantors': 'pam_unix,pam_localuser', 'op': 'PAM:accounting'}, 'uid': '1000', 'subj': 'random_ex:random_ex:random_ex:d3-d3:w0.c12'}