logic involved

... more often than not ...

Show Open Ports and Process IDs in Solaris

| Comments

I needed a list of all open ports and their respective processes of a Solaris system one day. Unfortunately lsof was not available. After some searching I ran across this script (note that it requires ptree, so it runs on Solaris only - bad luck for you Linux/Mac/Cygwin guys):

PCP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/usr/bin/ksh
#
# PCP (PID con Port)
# v1.07 20/05/2008 sam@unix.ms
#
# If you have a Solaris 8, 9 or 10 box and you can't
# install lsof, try this. It maps PIDS to ports and vice versa.
# It also shows you which peers are connected on which port.
# Wildcards are accepted for -p and -P options.
#
# The script borrows from Eric Steed's excellent "getport.sh" script.
#
#
if [ $# -lt 1 ]
then
  echo >&2 "usage: $0 [-p PORT] [-P PID] [-a ALL ] (Wildcards OK)"
  exit 1
fi
while getopts :p:P:a opt
do
  case "${opt}" in
    p ) port=${OPTARG};;
    P ) pid=${OPTARG};;
    a ) all=all;;
    [?]) # unknown flag
    echo >&2 "usage: $0 [-p PORT] [-P PID] [-a ALL ] (Wildcards OK) "
    exit 1;;
  esac
done

shift `expr $OPTIND - 1`
if [ $port ]
then
  # Enter the port number, get the PID
  #
  port=${OPTARG}
  echo "PID\tProcess Name and Port"
  echo "_________________________________________________________"
  for proc in `ptree -a | grep -v ptree | awk '{print $1};'`
  do
    result=`pfiles $proc 2> /dev/null| grep "port: $port"`
    if [ ! -z "$result" ]
    then
      program=`ps -fo comm -p $proc | tail -1`
      echo "$proc\t$program\t$port\n$result"
      echo "_________________________________________________________"
    fi
  done
elif [ $pid ]
then
  # Enter the PID, get the port
  #
  pid=$OPTARG
  # Print out the information
  echo "PID\tProcess Name and Port"
  echo "_________________________________________________________"
  for proc in `ptree -a | grep -v ptree | grep $pid| awk '{print $1};'`
  do
    result=`pfiles $proc 2> /dev/null| grep port:`
    if [ ! -z "$result" ]
    then
      program=`ps -fo comm -p $pid | tail -1`
      echo "$proc\t$program\n$result"
      echo "_________________________________________________________"
    fi
  done
elif [ $all ]
then
  # Show all PIDs, Ports and Peers
  #
  echo "PID\tProcess Name and Port"
  echo "_________________________________________________________"
  for pid in `ptree -a | grep -v ptree |sort -n | awk '{print $1};'`
  do
    out=`pfiles $pid 2>/dev/null| grep "port:"`
    if [ ! -z "$out" ]
    then
      name=`ps -fo comm -p $pid | tail -1`
      echo "$pid\t$name\n$out"
      echo "_________________________________________________________"
    fi
  done
fi
exit 0

Found at unix.ms.

shell

« Fighting painfully slow SMB shares Ubuntu 8.10RC »

Comments