Skip to content

Instantly share code, notes, and snippets.

@picatz
Created December 27, 2016 18:58
Show Gist options
  • Save picatz/34033f2a19cca4684457ba7460e78e4f to your computer and use it in GitHub Desktop.
Save picatz/34033f2a19cca4684457ba7460e78e4f to your computer and use it in GitHub Desktop.
require 'time'
# This CustomLogParser class is meant to help with
# the heavy lifting of sifting through the data
# you can find in a custom log file.
class CustomLogParser
attr_reader :data # parsed data
def initialize(args ={})
@data = [] # initialized as an empty array
parse(args[:file]) if args[:file]
end
def any_data?
! @data.empty?
end
def parse_file(file)
File.readlines(file).map(&:strip).each do |line|
# if we hadn't grep'd the info ( a little dangerous )
# a better regex match could be better here ¯\_(ツ)_/¯
next unless line['Failed login']
@data << parse_line(line)
end
end
def parse_line(line)
info = {} # empty hash
username, from_ip = line.split('Failed login attempt \'')[1].split('\'')
info[:username] = username
info[:ip] = from_ip.split.last
info[:time] = Time.parse(line.split[0..1].join(' '))
info
end
# return an array of usernames
def usernames
return false unless any_data?
@data.collect { |d| d[:username] }.uniq
end
# return an array of IP addresses
def ips
return false unless any_data?
@data.collect { |d| d[:ip] }.uniq
end
# return an array of times
def times
return false unless any_data?
@data.collect { |d| d[:time] }.uniq
end
end
# Typical Usage :
# create a new parser, optional pass in the file to parse
parser = CustomLogParser.new(:file => 'sample.log')
# check if there's any parsed data
parser.any_data?
# => true
# get an array of the uniq IP addresses in the parsed data
parser.ips
# => ["100.210.123.5", "13.208.250.62", "85.217.226.93", "73.238.170.32" ... ]
# get an array of the uniq usernames in the parsed data
parser.usernames
# => ["admin", "picat", "root"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment