title: Find currently connected port number SSH
body: <p>i'm creating a local simulator (not connected to internet) using SSH connection. I've started sshd on a particular range of port numbers and NATing a range of devices to those. I have to find the currently connected port number.</p>
  
  <p>OS CentOS 5.5
  OpenSSH 6.1</p>
  
  <p>I've done the following. It works for normal usage (manual user).But when trying a rigorous testing(automated) it seems like it is failing sometimes to find the port number.</p>
  
  <pre><code>#!/bin/bash
  
  WHOINFO=`who -m`
  
  USERNAME=`echo $WHOINFO | awk 'NR==1{print $1}'`
  PTSNUMBER=`echo $WHOINFO | awk 'NR==1{print $2}'`
  
  USERSTR=$USERNAME"@"$PTSNUMBER
  
  PID=`ps -eLf | grep $USERSTR | awk 'NR==1{print $3}'`
  
  if [ -z "$PID" ];
  then
          exit
  fi
  
  PORTSTR=`netstat -natp | grep $PID | awk 'NR==1{print $4}'`
  
  PORTNUMBER=${PORTSTR//*:/}
  
  echo $PORTNUMBER
  </code></pre>