Take the 2-minute tour ×

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.

OS CentOS 5.5 OpenSSH 6.1

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.


WHOINFO=`who -m`

USERNAME=`echo $WHOINFO | awk 'NR==1{print $1}'`
PTSNUMBER=`echo $WHOINFO | awk 'NR==1{print $2}'`


PID=`ps -eLf | grep $USERSTR | awk 'NR==1{print $3}'`

if [ -z "$PID" ];

PORTSTR=`netstat -natp | grep $PID | awk 'NR==1{print $4}'`


share|improve this question
your grep pattern for PID should be $PID/, as it is presented in that form in the output; otherwise you may incorrectly match ports that are numbered the same as the PID you're trying to match. –  Petesh May 9 '13 at 8:15
add comment

1 Answer

up vote 2 down vote accepted

An OpenSSH server will set the variable $SSH_CLIENT, which contains ip, client port and server port separated by spaces. To get the port number the current session is connected to, you can therefore use echo ${SSH_CLIENT##* }.

share|improve this answer
and if he wants to he can read that environment variable from the /proc/<pid>/environ file by piping it through tr '\0' '\n' –  Petesh May 9 '13 at 8:12
@that other guy Brilliant! my entire script now got reduced to an echo command. I couldn't find this variable. Thnx. –  Antarus May 9 '13 at 8:50
add comment

Your Answer


