List TCP ports with process

Hello,

One of our developers is asking for a command/script in Solaris similar to "netstat -anp" in Linux. He gave this output as an example:

root@xxx:~# netstat -anp | grep LISTEN
tcp        0      0 0.0.0.0:7937            0.0.0.0:*               LISTEN     16082/nsrexecd
tcp        0      0 0.0.0.0:7938            0.0.0.0:*               LISTEN     16082/nsrexecd
tcp        0      0 0.0.0.0:7940            0.0.0.0:*               LISTEN     16082/nsrexecd
tcp        0      0 0.0.0.0:7941            0.0.0.0:*               LISTEN     16082/nsrexecd
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN     4257/mysqld
tcp        0      0 127.0.0.1:5432          0.0.0.0:*               LISTEN     4331/postgres
tcp6       0      0 :::80                   :::*                    LISTEN     4403/apache2
tcp6       0      0 :::22                   :::*                    LISTEN     4163/sshd

Note, the command needs to be used on a Solaris 9 machine (no dtrace). I've been playing around with pfiles for an hour or so now and haven't come up with anything that seems 100% correct.

So I was wondering if you guys have any ideas on how to do this. I don't need a ready-made script (unless you have it), just some pointers to how I can produce a similar output.

Thanks. :wink:

If you have lsof installed:

lsof -i TCP|fgrep LISTEN

See my blog at
Chi Hung Chan: Which process listens to this port (in Solaris)

You should be able to modify the script to come up with something similar to netstat -anp. Just loop through all the LISTEN ports via 'netstat -an | grep LISTEN'

Thanks radoulov, I forgot about good ol' LSOF. It's not there, but I'll just install it on the machine. We've not been using lsof lately, since most of our machines are Solaris 10 now and it doesn't seem to give good results there (largely because it can't run in non-global zones).

So I guess my question changes. What do you guys use in Solaris 10 (and zones) as an "lsof -i | grep LISTEN" alternative? (dtrace allowed this time).

We don't have many Solaris 10 machines for now so I don't have experience with dtrace but DTrace Tools seem interesting.

Also found this: dtracetoolkit
Look for tcpsnoop.

Thanks both. :b:

Here is the ksh oneliner I use.
It needs some reformatting to suit your requirements:

pfexec pfiles `ls /proc` 2>/dev/null | egrep '^[0-9]|port:' | grep -v "AF_INET6" | sed -e 's/sockname: AF_INET//' -e 's/ *port: /:/'
2 Likes

Yep,
this is a good option. Another one, based on your idea:

pfiles /proc/* 2>&- | 
  nawk 'END {
  if (f) print p 
    }
/^[0-9]/ { 
    if (f) print p, RS 
    p = $0
    f = 0
  }
/INET / {
  sub(/.*INET/,"") 
  p = p ? p RS $0 : $0
  f = 1 
  }'