logparse / parsers / smbd.pyon commit update readme & docs (29c0dc8)
   1#
   2#   smbd.py
   3#   
   4#   Get login statistics for a samba server.
   5#   TODO: add feature to specify shares to check in config file
   6#
   7
   8import re
   9import glob
  10
  11from logparse.formatting import *
  12from logparse.util import readlog, resolve
  13from logparse import config
  14from logparse.load_parsers import Parser
  15
  16class Smbd(Parser):
  17
  18    def __init__(self):
  19        super().__init__()
  20        self.name = "smbd"
  21        self.info = "Get login statistics for a samba server."
  22
  23    def parse_log(self):
  24        logger.debug("Starting smbd section")
  25        section = Section("smbd")
  26        files = glob.glob(config.prefs.get("logs", "smbd") + "/log.*[!\.gz][!\.old]")    # find list of logfiles
  27        # for f in files:
  28
  29            # file_mod_time = os.stat(f).st_mtime
  30
  31            # Time in seconds since epoch for time, in which logfile can be unmodified.
  32            # should_time = time.time() - (30 * 60)
  33
  34            # Time in minutes since last modification of file
  35            # last_time = (time.time() - file_mod_time)
  36            # logger.debug(last_time)
  37
  38            # if (file_mod_time - should_time) < args.time:
  39                # print "CRITICAL: {} last modified {:.2f} minutes. Threshold set to 30 minutes".format(last_time, file, last_time)
  40            # else:
  41
  42            # if (datetime.timedelta(datetime.datetime.now() - datetime.fromtimestamp(os.path.getmtime(f))).days > 7):
  43                # files.remove(f)
  44        logger.debug("Found log files " + str(files))
  45        n_auths = 0         # total number of logins from all users
  46        sigma_auths = []    # contains users
  47
  48        for file in files:  # one log file for each client
  49
  50            logger.debug("Looking at file " + file)
  51
  52            # find the machine (ip or hostname) that this file represents
  53            ip = re.search('log\.(.*)', file).group(1)    # get ip or hostname from file path (/var/log/samba/log.host)
  54            host = resolve(ip, fqdn=config.prefs.get("smbd", "smbd-resolve-domains"))
  55            if host == ip and (config.prefs.get("smbd", "smbd-resolve-domains") != "ip" or config.prefs.get("logparse", "resolve-domains") != "ip"):    # if ip has disappeared, fall back to a hostname from logfile
  56                newhost = re.findall('.*\]\@\[(.*)\]', readlog(file))
  57                if (len(set(newhost)) == 1):    # all hosts in one file should be the same
  58                    host = newhost[0].lower()
  59
  60            # count number of logins from each user-host pair
  61            matches = re.findall('.*(?:authentication for user \[|connect to service .* initially as user )(\S*)(?:\] .*succeeded| \()', readlog(file))
  62            for match in matches:
  63                userhost = match + "@" + host
  64                sigma_auths.append(userhost)
  65                # exists = [i for i, item in enumerate(sigma_auths) if re.search(userhost, item[0])]
  66                # if (exists == []):
  67                #     sigma_auths.append([userhost, 1])
  68                # else:
  69                #     sigma_auths[exists[0]][1] += 1
  70                n_auths += 1
  71        auth_data = Data(subtitle=plural("login", n_auths) + " from")
  72        if (len(sigma_auths) == 1):             # if only one user, do not display no of logins for this user
  73            auth_data.subtitle += ' ' + sigma_auths[0][0]
  74            section.append_data(auth_data)
  75        else:       # multiple users
  76            auth_data.items = sigma_auths
  77            auth_data.orderbyfreq()
  78            auth_data.truncl(config.prefs.getint("logparse", "maxlist"))
  79            logger.debug("Found {0} samba logins".format(str(n_auths)))
  80        section.append_data(auth_data)
  81        logger.info("Finished smbd section")
  82        return section