Last active
August 29, 2015 14:04
-
-
Save jarfil/3d4ea72b5b0453b0ff1e to your computer and use it in GitHub Desktop.
Netstat listening sockets by processess
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
# get data | |
@net = `netstat -naptu`; | |
@ps = `ps xa`; | |
sort @net; | |
sort @ps; | |
$pid_offset = index($net[1], 'PID/'); | |
$pid_offset -= 3; # fix for some buggy netstat | |
my @data; | |
# populate data array with [pid[conn,*],*] | |
foreach my $conn (@net) { | |
# ignore non-listening sockets | |
next if $conn!~/LISTEN|^udp/; | |
$pid = substr $conn, $pid_offset; | |
$pid =~ s/^[^0-9]*//; # fix for some buggy netstat | |
$pid =~ s/\/.*//; | |
push @{ $data{$pid} }, $conn; | |
} | |
# add process info to data array as [pid.'p'[proc string],*] | |
foreach (@ps) { | |
$pid = $_; | |
$pid =~ s/^ *//; | |
$pid =~ s/ .*//; | |
# ignore processes with no sockets of interest | |
next if not $data{$pid}; | |
$data{$pid.'p'} = $_; | |
} | |
# only colorize to terminal | |
$enable_colors = -t STDOUT; | |
foreach my $k (sort {$a <=> $b} keys %data) { | |
# ignore keys with process info (process keys with socket data) | |
next if $k=~/p$/; | |
# print process info | |
if ($enable_colors) { | |
print "\e[1m".$data{$k."p"}."\e[0m"; | |
} else { | |
print $data{$k."p"}; | |
} | |
# print sockets | |
foreach ( @{ $data{$k} } ) { | |
print; | |
} | |
print "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment