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