logparse / parsers / cron_journald.pyon commit add docs (26e1b05)
   1#
   2#   cron_journald.py
   3#
   4#   List the logged (executed) cron jobs and their commands (uses journald module)
   5#
   6#   TODO: also output a list of scheduled (future) jobs
   7#
   8
   9from systemd import journal
  10
  11from logparse.formatting import *
  12from logparse import config
  13from logparse.load_parsers import Parser
  14
  15class CronJournald(Parser):
  16
  17    def __init__(self):
  18        super().__init__()
  19        self.name = "cron_journald"
  20        self.info = "List the logged (executed) cron jobs and their commands (uses journald module)"
  21
  22    def parse_log(self):
  23
  24        logger.debug("Starting cron section")
  25        section = Section("cron")
  26
  27        # Initiate journald reader
  28        j = journal.Reader()
  29        j.this_boot()
  30        j.this_machine()
  31        j.log_level(journal.LOG_INFO)
  32        j.add_match(_COMM="cron")
  33
  34        logger.info("Obtaining cron logs")
  35
  36        messages = [entry["MESSAGE"] for entry in j if "MESSAGE" in entry and " CMD " in entry["MESSAGE"]]
  37
  38        total_jobs = len(messages)
  39
  40        if total_jobs == 0:
  41            logger.warning("Couldn't find any cron commands")
  42            return 1
  43
  44        logger.info("Found " + str(total_jobs) + " cron jobs")
  45        section.append_data(Data("Total of " + plural("cron session", total_jobs) + " executed across all users"))
  46
  47        logger.debug("Analysing cron commands for each user")
  48        users = {}
  49
  50        for msg in messages:
  51            usr_cmd = re.search('\((\S+)\) CMD (.*)', msg)  # [('user', 'cmd')]
  52            if usr_cmd:
  53                if not usr_cmd.group(1) in users:
  54                    users[usr_cmd.group(1)] = []
  55                users[usr_cmd.group(1)].append(usr_cmd.group(2))
  56
  57        for usr, cmdlist in users.items():
  58            user_data = Data()
  59            user_data.subtitle = plural("cron session", len(cmdlist)) + " for " + usr
  60            user_data.items = ("`{0}`".format(cmd) for cmd in cmdlist)
  61            user_data.orderbyfreq()
  62            user_data.truncl(config.prefs.getint("logparse", "maxcmd"))
  63            section.append_data(user_data)
  64
  65        logger.info("Finished cron section")
  66
  67        return section