Apache visits with Perl

Here is another Perl script. This one given an Apache log file will tell you the number of hits per IP. Here is the code.

#!/usr/bin/perl -w

use strict;
use diagnostics;

if( $#ARGV != 0 ){
        print "Usage: ./parser.pl <logfile>\n"; 
        exit 1; }

# Opening logfile
open FILE, "$ARGV[0]" or die $!;

# Defining variables
my @lines = <FILE>;
my @ip;
my $items = scalar(@lines);
my ($i, $value); 
my %hits;

# Removing IP addresses from logfile and counting the hits per IP.
for ($i = 0; $i < $items; $i++)
        { @ip = split (/ /, $lines[$i]);
        if (exists $hits{$ip[0]}) {
                $hits{$ip[0]} = $hits{$ip[0]}+1; 
                chomp($hits{$ip[0]}); } 
        else {  $hits{$ip[0]} = 1; } 
        }

# Ordering and printing the hits per IP.
foreach $value (sort {"$hits{$b}" <=> "$hits{$a}" } keys %hits)
        { print "$value made $hits{$value} hits.\n"; }

Here is an usage example.

xavi@debianserver:~/Perl$ ./parser.pl /tmp/apachelog 
12.130.86.9 made 106 hits.
208.111.39.192 made 89 hits.
67.195.114.231 made 42 hits.
98.14.22.97 made 27 hits.
208.54.45.78 made 17 hits.
213.5.71.12 made 16 hits.
199.106.237.37 made 15 hits.
66.249.67.212 made 15 hits.
208.54.45.62 made 12 hits.
87.250.252.242 made 9 hits.
174.121.74.234 made 6 hits.
188.187.102.74 made 6 hits.
208.54.45.72 made 5 hits.
64.40.121.184 made 4 hits.
206.196.125.114 made 3 hits.
207.46.13.94 made 2 hits.
220.181.146.169 made 2 hits.
142.166.170.101 made 2 hits.
220.181.94.225 made 2 hits.
142.166.170.100 made 2 hits.
65.52.108.60 made 2 hits.
207.46.199.182 made 2 hits.
207.46.13.101 made 2 hits.
208.54.45.56 made 2 hits.
209.2.233.223 made 1 hits.
67.210.218.102 made 1 hits.
66.249.67.66 made 1 hits.
220.181.7.54 made 1 hits.
207.46.199.199 made 1 hits.

As usual, suggestions are always welcome.

Leave a Reply