Pages

21 August 2010

nstree.pl

#!/usr/bin/perl
# $Id: nstree, v 0.1a1 2010/03/06 11:32:16 PST epixoip Exp $
# shows essential information about network daemons in a formatted tree view. it's like 'pstree,' but for netstat!

use strict;
my %daemons;

die "error: nstree is for linux!\n" if $^O ne 'linux';
die "error: nstree will not display accurate results if run as an unprivileged user.\n" if $<; sub trim { my $line = shift; $line =~ s/^\s+//; $line =~ s/\s+$//; return $line; } foreach ( qx{ (LC_ALL=C /bin/netstat -A inet --tcp -nlp 2>&1) } ) {

next if ! /LISTEN/i;

my @lines = split(/\s+/);
my ( $laddr, $lport ) = split(':', $lines[3]);
my ( $pid, $proc ) = split('/', $lines[6]);

my $args = &trim(`/bin/ps h -o args $pid 2>/dev/null`);
my $euid = &trim(`/bin/ps h -o euid $pid 2>/dev/null`);
my $egid = &trim(`/bin/ps h -o egid $pid 2>/dev/null`);

$daemons{$laddr}{$lport} = { args => $args, pid => $pid, euid => $euid, egid => $egid };
}

foreach ( qx{ (LC_ALL=C /bin/netstat -A inet --tcp -np 2>&1) } ) {

next if ! /ESTABLISHED/i;

my @lines = split(/\s+/);
my ( $laddr, $lport ) = split(':', $lines[3]);
my ( $pid, $proc ) = split('/', $lines[6]);
my $cmd = &trim(`ps h -o args $pid 2>/dev/null`);


if ( ref($daemons{$laddr}{$lport}) eq 'HASH' ) {

push(@{$daemons{$laddr}{$lport}{'connections'}}, { laddr=> $laddr, raddr => $lines[4], what => $cmd });

} elsif ( ref($daemons{'0.0.0.0'}{$lport}) eq 'HASH' ) {

push(@{$daemons{'0.0.0.0'}{$lport}{'connections'}}, { laddr => $laddr, raddr => $lines[4], what => $cmd });

}

}

print "\n";

my ( $len, $plen );

for my $addr ( keys %daemons ) {

if (length($addr) > $plen) { $len = length($addr); }

$plen = length($addr);

}

my $toffset;
for (my $i=0; $i<= ($len + 1); $i++) { $toffset = $toffset . ' '; } for my $addr ( sort { $a <=> $b } keys %daemons ) {

my $offset = $len - length($addr);

my $ioffset;
for (my $i=0; $i<=$offset; $i++) { $ioffset = $ioffset . '-'; } print "$addr$ioffset-+\n"; for my $port ( sort { $a <=> $b } keys %{$daemons{$addr}} ) {

print "$toffset|-- tcp/$port\n";
print "$toffset| |-- cmd: " . $daemons{$addr}{$port}{'args'} . "\n";
print "$toffset| |-- pid: " . $daemons{$addr}{$port}{'pid'} .
' (euid=' . $daemons{$addr}{$port}{'euid'} .
', egid=' . $daemons{$addr}{$port}{'egid'} . ")\n";
print "$toffset| |-- connections: " .
( defined @{$daemons{$addr}{$port}{'connections'}} ? @{$daemons{$addr}{$port}{'connections'}} : '0' ) . "\n";

foreach my $conn (@{$daemons{$addr}{$port}{'connections'}}) {
print "$toffset| |-- " . ${$conn}{'raddr'} . ' => ' .
${$conn}{'laddr'} . ' (' .
${$conn}{'what'} . ")\n";
}

}

}

print "\n\n";

0 comments: