Find the current SSH port number

I am creating a local simulator (not connected to the Internet) using an SSH connection. I started using sshd for a specific range of port numbers and NATing a number of devices for them. I need to find the current port number.

OS CentOS 5.5 OpenSSH 6.1

I did the following. It works for normal use (manual user). But when trying a rigorous testing (automated), it seems that sometimes he can’t 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 
+6
source share
1 answer

The OpenSSH server will set the $SSH_CLIENT variable, 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 that the current session is connected to, you can use echo ${SSH_CLIENT##* } .

+12
source

Source: https://habr.com/ru/post/944603/


All Articles