我有一个脚本,将由一个人使用SSH登录到服务器运行。

是否有一种方法可以自动找出用户从哪个IP地址连接?

当然,我可以询问用户(这是程序员的工具,所以这没有问题),但如果我自己找到答案,那就更好了。


当前回答

who am i | awk '{print $5}' | sed 's/[()]//g' | cut -f1 -d "." | sed 's/-/./g'


export DISPLAY=`who am i | awk '{print $5}' | sed 's/[()]//g' | cut -f1 -d "." | sed 's/-/./g'`:0.0

当通过ssh登录并需要显示远程X时,我使用它来确定会话的DISPLAY变量。

其他回答

搜索“myusername”帐户的SSH连接;

获取第一个结果字符串;

以第五纵队为例;

通过“:”分割并返回第一部分(端口号不需要,我们只需要IP):

Netstat -tapen | grep "sshd: myusername" | head -n1 | awk '{split($5, a, ":");打印一个[1]}’


另一种方法:

我是谁| awk '{l = length($5) - 2;打印substr($ 5,2, l)}'

who am i | awk '{print $5}' | sed 's/[()]//g' | cut -f1 -d "." | sed 's/-/./g'


export DISPLAY=`who am i | awk '{print $5}' | sed 's/[()]//g' | cut -f1 -d "." | sed 's/-/./g'`:0.0

当通过ssh登录并需要显示远程X时,我使用它来确定会话的DISPLAY变量。

您可以通过SSH库(https://code.google.com/p/sshxcute)以编程方式获取它。

public static String getIpAddress() throws TaskExecFailException{
    ConnBean cb = new ConnBean(host, username, password);
    SSHExec ssh = SSHExec.getInstance(cb);
    ssh.connect();
    CustomTask sampleTask = new ExecCommand("echo \"${SSH_CLIENT%% *}\"");
    String Result = ssh.exec(sampleTask).sysout;
    ssh.disconnect();   
    return Result;
}

改进之前的答案。给出ip地址而不是主机名。——ip在OS X上不可用。

who am i --ips|awk '{print $5}' #ubuntu 14

更通用的是,OS X 10.11将5美元改为6美元:

WORKSTATION=`who -m|awk '{print $5}'|sed 's/[()]//g'`
WORKSTATION_IP=`dig +short $WORKSTATION`
if [[ -z "$WORKSTATION_IP" ]]; then WORKSTATION_IP="$WORKSTATION"; fi
echo $WORKSTATION_IP
 who | cut -d"(" -f2 |cut -d")" -f1