bash 如何从 $SSH_CLIENT 获取 IP 地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2230478/
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-17 21:39:54  来源:igfitidea点击:

How to get the IP address from $SSH_CLIENT

bash

提问by prosseek

$SSH_CLIENT has IP address with some port info, and echo $SSH_CLIENT gives me '10.0.40.177 52335 22', and Running

$SSH_CLIENT 有一些端口信息的 IP 地址,echo $SSH_CLIENT 给我'10.0.40.177 52335 22',然后运行

if [ -n "$SSH_CONNECTION" ] ; then for i in $SSH_CLIENT do echo $i done fi

if [ -n "$SSH_CONNECTION" ] ; then for i in $SSH_CLIENT do echo $i done fi

gives me

给我

  • 10.0.40.177
  • 52335
  • 22
  • 10.0.40.177
  • 52335
  • 22

And I see the first element is the IP address.

我看到第一个元素是 IP 地址。

Q : How can I get the first element of $SSH_CLIENT? ${SSH_CLIENT[0]} doesn't work.

问:如何获取 $SSH_CLIENT 的第一个元素?${SSH_CLIENT[0]} 不起作用。

回答by Ignacio Vazquez-Abrams

sshvars=($SSH_CLIENT)
echo "${sshvars[0]}"

or:

或者:

echo "${SSH_CLIENT%% *}"

回答by ghostdog74

you can use set --eg

你可以使用set --例如

$ SSH_CLIENT="10.0.40.177 52335 22"
$ set -- $SSH_CLIENT
$ echo   # first "element"
10.0.40.177
$ echo   # second "element"
52335
$ echo 
22

回答by Emil

For strings, as is the case here, the <<<operator may be used:

对于字符串,就像这里的情况一样,<<<可以使用运算符:

$ read ipaddress outport inport <<< $SSH_CLIENT

See e.g: Linux Bash: Multiple variable assignment. Don't do this with binary input though: Is there a binary safe <<< in bash?

参见例如:Linux Bash:多变量赋值。但是不要用二进制输入来做这个:bash 中是否有二进制安全<<<?

回答by vineetv2821993

You can get it programmatic way via ssh library (https://code.google.com/p/sshxcute)

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

回答by bayuah

If you prefer awk:

如果你喜欢awk

$ SSH_CLIENT="10.0.40.177 52335 22"
$ echo $SSH_CLIENT|awk '{print }' # first element
10.0.40.177
$ echo $SSH_CLIENT|awk '{print }' # second element
52335
$ echo $SSH_CLIENT|awk '{print }' # third element
22

回答by Howard

I use this in my .bash_profile, and it works beautifully.

我在我的 .bash_profile 中使用了它,它运行良好。

if [ -n "$SSH_CONNECTION" ] ;
    then
    echo $SSH_CLIENT | awk '{print }'
fi