w3ntp has asked for the wisdom of the Perl Monks concerning the following question:

I am looking for a Perl Module that will Identify all connections to a given TCP port on a Solaris box. It would also identify any local running Processes that are attached to the port or any IP addresses attached to the port. Sort of like a combination ov netstat and "ps -ef". There is a freeware version of "lsof" that does exactly what I need "lsof -i node@4100", However, It would be nice if there was an equivalent version in PERL. thanks W3NTP

Replies are listed 'Best First'.
Re: Perl Version of Solaris LSOF Utility
by hawtin (Prior) on Nov 06, 2003 at 18:32 UTC

    I had to do a similar thing in an environment where I had limited root access and was not allowed to have lsof.

    Here is my code (it worked for me your milage may vary)

    #!/bin/env perl # Find out which processes have a particular # socket open use strict; # Just to send you off to the Camel $,=", "; my $port_to_lookfor = '\d+'; $port_to_lookfor = shift(@ARGV) if(@ARGV); my $os = &deduce_os(); # What processes are running? opendir(PROC,"/proc"); my @processes = readdir(PROC); closedir(PROC); my %counts; if($os eq "solaris") { foreach my $proc (@processes) { next unless($proc =~ /^\d+$/); # Really ought to only check our own processes here my $ret = `pfiles $proc 2>&1`; while($ret =~ s/port:\s*($port_to_lookfor)//i) { $counts{"$proc:$1"} += 1; } } } elsif($os eq "linux") { # This depends on how your kernel is configured # pretend it will work anywhere #my $ret = `ls -l /proc/$proc/fd 2>&1`; #while($ret =~ s/socket:\[($port_to_lookfor)\]//i) # { # $counts{"$proc:$1"} += 1; # } my $ret = `/usr/sbin/lsof | grep IPv4`; foreach my $l (split("\n",$ret)) { if($l =~ /^\D*(\d+)[^:]:($port_to_lookfor)/) { $counts{"$1:$2"} += 1; } } } foreach my $proc (sort numerically keys(%counts)) { if($proc =~ /^(\d+)\:(\d+)$/) { printf "Process: %-7d - Port: %-7d - Count %-4d\n", $1,$2,$counts{$proc}; } } exit(0); sub numerically { return($a <=> $b); } sub deduce_os { # Take a simplstic view (Should use the magic variable) my $uname = `uname -msrv`; chomp($uname); return "linux" if($uname =~ /Linux/i); return "solaris" if($uname =~ /SunOS 5/i); return "unknown"; }
Re: Perl Version of Solaris LSOF Utility
by sweetblood (Prior) on Nov 06, 2003 at 15:58 UTC
    Are you looking for advice on how one would write this or looking for someone to do it for you? Why would want a Perl equivalent if there is already a freeware version?
Re: Perl Version of Solaris LSOF Utility
by Anonymous Monk on Nov 06, 2003 at 15:10 UTC
    just use lsof and parse the output