8a6dcd3954a0612836611d7ac8074a9d4c4bd7fe
   1#
   2#   sudo.py
   3#   
   4#   Get number of sudo sessions for each user
   5#
   6#   NOTE: This file is now deprecated in favour of the newer journald mechanism
   7#   used in sudo-journald.py. This parser is still functional but is slower and
   8#   has less features. Please switch over if possible.
   9#
  10
  11import re
  12
  13from logparse.formatting import *
  14from logparse.util import readlog
  15from logparse.config import prefs
  16from logparse.load_parsers import Parser
  17
  18class Sudo(Parser):
  19
  20    def __init__(self):
  21        super().__init__()
  22        self.name = "sudo"
  23        self.info = "Get number of sudo sessions for each user"
  24        self.deprecated = True
  25        self.successor = "sudo_journald"
  26
  27    def parse_log(self):
  28        logger.debug("Starting sudo section")
  29        section = Section("sudo")
  30        logger.debug("Searching for matches in {0}".format(prefs.get("logs", "auth")))
  31        umatches = re.findall('.*sudo:session\): session opened.*', readlog(prefs.get("logs", "auth")))
  32        num = sum(1 for line in umatches)    # total number of sessions
  33        users = []
  34        data = []
  35        for match in umatches:
  36            user = re.search('.*session opened for user root by (\S*)\(uid=.*\)', match).group(1)
  37            exists = [i for i, item in enumerate(users) if re.search(user, item[0])]
  38            if (exists == []):
  39                users.append([user, 1])
  40            else:
  41                users[exists[0]][1] += 1
  42        commands = []
  43        cmatches = re.findall('sudo:.*COMMAND\=(.*)', readlog(prefs.get("logs", "auth")))
  44        for cmd in cmatches:
  45            commands.append(cmd)
  46        logger.debug("Finished parsing sudo sessions")
  47
  48        auth_data = Data(subtitle=plural("sudo session", num) + " for")
  49
  50        if (len(users) == 1):
  51            logger.debug("found " + str(num) + " sudo session(s) for user " + str(users[0]))
  52            auth_data.subtitle += ' ' + users[0][0]
  53        else:
  54            for user in users:
  55                auth_data.items.append(user[0] + ' (' + str(user[1]) + ')')
  56            logger.debug("found " + str(num) + " sudo sessions for users " + str(data))
  57        section.append_data(auth_data)
  58
  59        if (len(commands) > 0):
  60            command_data = Data(subtitle="top sudo commands")
  61            commands = backticks(commands)
  62            command_data.items = commands
  63            command_data.orderbyfreq()
  64            command_data.truncl(prefs.getint("logparse", "maxcmd"))
  65            section.append_data(command_data)
  66
  67        logger.info("Finished sudo section")
  68
  69        return section