#!/bin/bash netstat -tn | perl -n -e ' BEGIN { %in = (); %out = (); %states = (); } { next if $. < 3; my ($local, $remote, $state) = (split(/\s+/, $_))[3,4,5]; my ($laddr, $lport) = split(/:/, $local); my ($raddr, $rport) = split(/:/, $remote); $states{$state}++; next if ($laddr eq "127.0.0.1" || $raddr eq "127.0.0.1"); if ($rport > $lport) { $in{$lport}++; $ia{$raddr}++; } else { $out{$rport}++; $oa{$raddr}++; } } END { print "Connections by state\n"; for my $s (reverse sort {$states{$a} <=> $states{$b}} keys %states) { printf "%-12s %s\n", $s, $states{$s}; } print "Connections inbound by port (exl 127.0.0.1)\n"; for my $s (reverse sort {$in{$a} <=> $in{$b}} keys %in) { printf "%-12s %s\n", $s, $in{$s}; } print "Connections outbound by port (exl 127.0.0.1)\n"; for my $s (reverse sort {$out{$a} <=> $out{$b}} keys %out) { printf "%-12s %s\n", $s, $out{$s}; } print "Connections inbound by client addr (> 5) (exl 127.0.0.1)\n"; for my $s (reverse sort {$ia{$a} <=> $ia{$b}} keys %ia) { next unless $ia{$s} > 5; printf "%-16s %s\n", $s, $ia{$s}; } print "Connections outbound by server addr (> 5) (exl 127.0.0.1)\n"; for my $s (reverse sort {$oa{$a} <=> $oa{$b}} keys %oa) { next unless $oa{$s} > 5; printf "%-16s %s\n", $s, $oa{$s}; } } ' exit 0