Find currently connected port number SSH
14,212
An OpenSSH server will set the variable $SSH_CLIENT
, which contains the current ip, client port and server port separated by spaces:
$ echo "$SSH_CLIENT"
127.0.0.1 59064 22
To get the port number the current session is connected to, you can therefore use echo ${SSH_CLIENT##* }
.
Author by
Antarus
Updated on July 09, 2022Comments
-
Antarus almost 2 years
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.
#!/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
-
Anya Shenanigans almost 11 yearsand if he wants to he can read that environment variable from the
/proc/<pid>/environ
file by piping it throughtr '\0' '\n'
-
Antarus almost 11 years@that other guy Brilliant! my entire script now got reduced to an echo command. I couldn't find this variable. Thnx.