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

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

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


当前回答

netstat -tapen | grep ssh | awk '{ print $10}'

输出:

在我的实验中有两个

netstat -tapen | grep ssh | awk '{ print $4}' 

给出IP地址。

输出:

127.0.0.1:22 # in my experiment

但结果和其他用户混在一起。它需要更多的工作。

其他回答

netstat -tapen | grep ssh | awk '{ print $4}'

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

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”并离开循环。

在你的Linux机器上输入以下命令:

who

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

我在Debian 10上从who -m——ips得到以下输出:

root pts/0 12月4日06:45 123.123.123.123

看起来像一个新的列被添加,所以{打印$5}或“采取第五列”尝试不再工作。

试试这个:

who -m --ips | egrep -o '([0-9]{1,3}\.){3}[0-9]{1,3}'

来源:

@Yvan对@AlexP回答的评论 @Sankalp的回答