I don't have a lot to say, but this is my little bit.

Monday, October 29, 2012

tallylog.pl - Find Matching Log Entries

This is a bit of perl code which finds and prints only logfile entries matching desired variables.
#!/usr/bin/perl
use strict;

# tallylog.pl
# by Nicholas Keene, September 2012
# this script takes the
# name of a log file and the name of a service then processes a log file to print summary information
# based on the inputs.

my ($logfile, $service) = @ARGV;

if (!-e $logfile) {
    print "Specified logfile does not exist.\n";
} elsif (-d $logfile) {
    print "Specified logfile must be a file, not a Directory.\n";
} else {
 TallyLogFile($logfile, $service);
}

# TallyLogFile
# Takes the name of a logfile and the name of a service
# Prints how many times each user accessed the log file from an IP address
# Note: only counts authorized access, not denied access
# Note: does not sort output; output order is unspecified
sub TallyLogFile { 
 my $logfile = shift;
 my $service = shift;
 my %users = ();
 
 open LOGFILE, "<", $logfile;

 while () {
  if( $_ =~ m/^.*Authorized User \((.*)\) for service "$service" from (.*).$/) {
   #print "Found: $1, $2, $3\n";
   if(!defined $users{$1} or !defined $users{$1}{$2}) {
    $users{$1}{$2} = 1;
   } else {
    $users{$1}{$2}++;
   }
  }
 }
 
 foreach my $user (keys %users) {
  print "$user\n";
  foreach my $ip (keys %{ $users{$user} } ) {
   my $count = $users{$user}{$ip};
   printf "%17s: %s\n", $ip, $count;
  }
 }
}

No comments:

Post a Comment