bash 查找当前连接的端口号 SSH

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16456152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:23:32  来源:igfitidea点击:

Find currently connected port number SSH

linuxbashshellssh

提问by Antarus

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.

我正在使用 SSH 连接创建一个本地模拟器(未连接到互联网)。我已经在特定范围的端口号上启动了 sshd,并将一系列设备转换为这些端口号。我必须找到当前连接的端口号。

OS CentOS 5.5 OpenSSH 6.1

操作系统 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 }'`
PTSNUMBER=`echo $WHOINFO | awk 'NR==1{print }'`

USERSTR=$USERNAME"@"$PTSNUMBER

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

if [ -z "$PID" ];
then
        exit
fi

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

PORTNUMBER=${PORTSTR//*:/}

echo $PORTNUMBER

回答by that other guy

An OpenSSH server will set the variable $SSH_CLIENT, which contains the current ip, client port and server port separated by spaces:

OpenSSH 服务器将设置变量$SSH_CLIENT,其中包含以空格分隔的当前 ip、客户端端口和服务器端口:

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

要获取当前会话连接的端口号,您可以使用echo ${SSH_CLIENT##* }.