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

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

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


当前回答

您可以通过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;
}

其他回答

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

您可以通过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;
}
netstat -tapen | grep ssh | awk '{ print $10}'

输出:

在我的实验中有两个

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

给出IP地址。

输出:

127.0.0.1:22 # in my experiment

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

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

who

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

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