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

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

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


当前回答

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

获取第一个结果字符串;

以第五纵队为例;

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

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


另一种方法:

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

其他回答

通常在/var/log/messages(或类似的,取决于你的操作系统)中有一个日志条目,你可以用用户名来grep它。

您可以通过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;
}
 who | cut -d"(" -f2 |cut -d")" -f1

一个有很多答案的旧帖子,但没有一个是我想要的,所以我贡献了我的:

sshpid=$$
sshloop=0
while [ "$sshloop" = "0" ]; do
        if [ "$(strings /proc/${sshpid}/environ | grep ^SSH_CLIENT)" ];
then
                read sshClientIP sshClientSport sshClientDport <<< $(strings /proc/${sshpid}/environ | grep ^SSH_CLIENT | cut -d= -f2)
                sshloop=1
        else
                sshpid=$(cat /proc/${sshpid}/status | grep PPid | awk '{print $2}')
                [ "$sshpid" = "0" ] && sshClientIP="localhost" && sshloop=1
        fi
done

此方法兼容直接ssh、sudoed用户和screen会话。它将遍历进程树,直到找到带有SSH_CLIENT变量的pid,然后将其IP记录为$sshClientIP。如果它在树上走得太远,它将把IP记录为“localhost”并离开循环。

尝试以下方法获取IP地址:

who am i|awk '{ print $5}'