Friday, December 4, 2009

[Level 3] Get process pid which open port!

How to get your process that open port.
The following will help you to check it!

#!/usr/bin/bash
showUsage() {
  cat <<EOF
Usage:
  $0 [port/pid/program](sort column, default is sort by 'port'.)
Ex.
  $0 1/port
  $0 2/pid
  $0 3/program
EOF
}

####################################### main

typeset -i nSortKey
case $1 in
1|port|"")
  sFlag="-n"
  nSortKey=1
  ;;
2|pid)
  sFlag="-n"
  nSortKey=2
  ;;
3|program)
  nSortKey=3
  ;;
*)
  showUsage
  exit 0
  ;;
esac

echo "port\tpid\tcmd"
ps -eo pid,comm | while read pid cmd
do
  pfiles $pid 2> /dev/null | grep port: | awk "{printf(\"%s\t%s\t%s\n\",\$5,\"$pid\",\"$cmd\")}"
done | sort $sFlag -u -k $nSortKey 



Wish this helps.

regards,
Stanley Huang