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
In putty configuration, click name in the Saved Sessions, then click Load button, one can see the port number in the above Port field.
Open a CMD prompt. Type in the command: netstat -ano -p tcp. You'll get an output similar to this one. Look-out for the TCP port in the Local Address list and note the corresponding PID number.
The default SSH port is 22. It is not a coincidence.
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##* }
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With