Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find currently connected port number SSH

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
like image 560
Antarus Avatar asked May 09 '13 06:05

Antarus


People also ask

How do I find my port number in putty?

In putty configuration, click name in the Saved Sessions, then click Load button, one can see the port number in the above Port field.

How do I find my port number in terminal?

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.

Is SSH always port 22?

The default SSH port is 22. It is not a coincidence.


1 Answers

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##* }.

like image 187
that other guy Avatar answered Sep 27 '22 18:09

that other guy