#!/usr/bin/perl -w use strict; use Net::DNS; use constant TOP_NUMBER => 5; my $ip = shift; if (!$ip) { die "ip not specified"; } # Initialization my %sources; my %destinations; my $total_in = 0; my $total_out = 0; my $res = Net::DNS::Resolver->new; # Read stdin ipacct lines while (<>) { chomp; my @items = split /\s+/; # src_IP src_Port dst_IP dst_Port Proto packets bytes unixtime # Outbound traffic if ($items[0] eq $ip) { if (!exists($destinations{$items[2]})) { $destinations{$items[2]} = int($items[6]); } else { $destinations{$items[2]} += int($items[6]); } $total_out += int($items[6]); } # Inbound traffic if ($items[2] eq $ip) { if (!exists($sources{$items[0]})) { $sources{$items[0]} = int($items[6]); } else { $sources{$items[0]} += int($items[6]); } $total_in += int($items[6]); } } # Do output: print "=========== SOURCES ============\n\n"; while (my ($k,$v) = each (%sources)) { print "IP: $k, bytes: $v\n"; } print "\n\n=========== DESTINATIONS ============\n\n"; while (my ($k,$v) = each (%destinations)) { print "IP: $k, bytes: $v\n"; } # Sort hashes my @sort_src = sort { $sources{$b} <=> $sources{$a} } keys %sources; my @sort_dst = sort { $destinations{$b} <=> $destinations{$a} } keys %destinations; # Output top sources my $limit = TOP_NUMBER; if (scalar (@sort_src) < $limit) { $limit = scalar (@sort_src); } print "\n\n=========== TOP SOURCES ============\n\n"; for (my $i = 0; $i < $limit; $i ++) { my $cur_bytes = $sources{$sort_src[$i]}; my $query = $res->search("$sort_src[$i]"); if ($query) { foreach my $rr ($query->answer) { next unless $rr->type eq "PTR"; print "IP: $sort_src[$i] (" . $rr->ptrdname . "), bytes: $cur_bytes\n"; last; } } else { print "IP: $sort_src[$i], bytes: $cur_bytes\n"; } } # Output top destinations $limit = TOP_NUMBER; if (scalar (@sort_dst) < $limit) { $limit = scalar (@sort_dst); } print "\n\n=========== TOP DESTINATIONS ============\n\n"; for (my $i = 0; $i < $limit; $i ++) { my $cur_bytes = $destinations{$sort_dst[$i]}; my $query = $res->search("$sort_dst[$i]"); if ($query) { foreach my $rr ($query->answer) { next unless $rr->type eq "PTR"; print "IP: $sort_dst[$i] (". $rr->ptrdname . "), bytes: $cur_bytes\n"; last; } } else { print "IP: $sort_dst[$i], bytes: $cur_bytes\n"; } } # Output total bytes print "\n\n=========== TOTAL ============\n\nIN: $total_in bytes, OUT: $total_out bytes\n";