0

I have an init script for an application, and know the PID is available from the script. I am trying to add some logic to the status command to output the TCP listen ports associated with the PID. I read through the answers to How to list all the current network connections for a given PID?, but I'm still not sure which fits best in this case.

This is non-critical, but I'd like it to make it as portable as possible, and ensure it fails gracefully if it can't run. So far I've come up with a couple alternatives, but I'm not sure which is likely to be the most portable (both work on my test environment), or if there is a better way to accomplish this.

Here's what I've come up with so far:

lsof -anP -i -p $APP_PID -sTCP:LISTEN -Fn | \
sed -e '/^n/ !d; /127.0.0.1/ d; s/n.*:\(.*\)/\1/' | sort -h | paste -s -d','

netstat -tlpn | grep $APP_PID | \
awk '$4!~/127.0.0.1/ {split($4,listener,":"); print listener[2]}' | \
sort -h | paste -s -d','

(I could probably work that grep into the awk, but I'm not that familiar with awk)

Both output a list like so: 4500,9233,9475,27000

Is there any good way to test which I should run if one command vs another is available on the target machine? Or is one combination of commands superior to another in terms of portability generally? (You may assume a Linux target, and outside of echo the script only uses LSB defined functions)

  • 1
    lsof is nowhere near portable. – Satō Katsura Nov 14 '17 at 15:30
  • @SatōKatsura As far as I can tell, there isn't really a portable option to do what I want. My goal is simply to achieve the version which is most likely to work, and fail gracefully otherwise. – BryKKan Nov 14 '17 at 15:37
  • 1
    Well, netstat output is not portable, and on most non-Linux systems there is no equivalent to netstat -p. lsof output is portable, but lsof itself may not be installed, or it may not exist for the target OS. Also $4!~/127.0.0.1/ in your awk matches too much, use index() instead. – Satō Katsura Nov 14 '17 at 15:48
  • @SatōKatsura Thanks. I'd rather fail entirely than output garbage. So lsof sounds like the better option. I notice that I failed to escape the '.' character in both regexes, but I'm a little confused by your recommendation to use index. The purpose of the $4!~/127.0.0.1/ was similar to the sed /127.0.0.1/ d, to remove loopback listeners. – BryKKan Nov 14 '17 at 22:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.