in reply to Perl Version of Solaris LSOF Utility
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"; }
|
|---|