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"; }

In reply to Re: Perl Version of Solaris LSOF Utility by hawtin
in thread Perl Version of Solaris LSOF Utility by w3ntp

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.