Sep 252012
 

Finally one that looks at a process and tells you what ports its listening to.

WPCM450 /tmp]$ ps |grep ssh
 1263 root       4532 S   /sbin/sshd -g 60
 9730 root       9412 S   sshd: root@pts/0    
10571 root       3556 R   grep ssh
[WPCM450 /tmp]$ ./lsof-net-pid.sh 1263
PID 1263 is listening on tcp6:22
PID 1263 is listening on tcp:22

Small script. Vicious haxx0r sed line in there (written by someone else, obviously!)

:

#
# busybox - find network ports being listened to by pid
#

if [ "X$1" == "X" ] ; then
   echo Usage: $0 pid
   exit 1
fi

pid=$1
fd="/proc/$pid/fd"

# this gives inodes of sockets pid is listening to
inodes=`/bin/ls -l $fd | grep socket: | awk '{print $NF}' | sed -e 's/socket:\[//' -e 's/\]//'`

if [ "X$inodes" == "X" ] ; then
   echo $pid isn\'t listening to any external network ports I could find
   exit 2
fi

for inode in $inodes ; do
   # echo $inode
   # check out if any matches in /proc/net (busybox doesn't have per pid net entries)

   # this line will print out something like /proc/net/tcp, 00000000000000000000000000000000:0016, 4535
   awk '$10 == '"$inode"' {print FILENAME, $2, $10}' /proc/net/?cp* | while read proto port inode ; do
      if [ "X$proto" != "X" ] ; then
        echo -n "PID $pid is listening on "
        echo -n $proto | sed 's@^.*net/@@'
        echo -n ":"
      #
      # more busybox hoop jumping... sometimes like ice skating with roller skates
      #
      # the amazing sed+ stuff courtesy of http://stackoverflow.com/questions/3675012/hex-to-dec-con
      #
        echo $port | awk -F: '{print $2}' | sed 's,\(..\)\(..\)\(..\)\(..\),\4\3\2\1,g' | (read hex; echo $(( 0x${hex} )))
      fi
   done

done

Sorry, the comment form is closed at this time.