2010-12-15

Perl throw-away script: netstat report on a certain port.

SYN* means a connection is opening. *WAIT means a connection is closing.


#!/usr/bin/perl -w

use strict;
use warnings;

use Getopt::Std;

our %opt;
getopt('p', \%opt);

my $port = 80;
if (exists $opt{'p'}) {
$port = $opt{'p'};
}

my @lines = qx{ /usr/bin/netstat -an };

my %status;

for my $line (@lines) {
my @fields = split /\s+/, $line;

next if !exists $fields[3];
next unless $fields[0] =~ /^tcp/;

if ($fields[3] =~ /\.$port$/) {
$status{$fields[-1]}++;
}
}

my $total;
for my $key (keys %status) {
print "$key = $status{$key}\n";
$total += $status{$key};
}

print '-' x 15 . "\n";
print "total = $total\n";


Example of running it:

me@mybox:/~
$ ./netstat_port_report.pl -p 8054
CLOSE_WAIT = 1
FIN_WAIT_2 = 166
ESTABLISHED = 148
LISTEN = 1
---------------
total = 316

No comments:

Post a Comment