[英]How to get the IP address from $SSH_CLIENT
$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
gives me给我
And I see the first element is the IP address.我看到第一个元素是 IP 地址。
Q : How can I get the first element of $SSH_CLIENT?问:如何获取 $SSH_CLIENT 的第一个元素? ${SSH_CLIENT[0]} doesn't work.
${SSH_CLIENT[0]} 不起作用。
sshvars=($SSH_CLIENT)
echo "${sshvars[0]}"
or:或者:
echo "${SSH_CLIENT%% *}"
you can use set --
eg你可以使用
set --
例如
$ SSH_CLIENT="10.0.40.177 52335 22"
$ set -- $SSH_CLIENT
$ echo $1 # first "element"
10.0.40.177
$ echo $2 # second "element"
52335
$ echo $3
22
For strings, as is the case here, the <<<
operator may be used:对于字符串,就像这里的情况一样,可以使用
<<<
运算符:
$ read ipaddress outport inport <<< $SSH_CLIENT
See eg: Linux Bash: Multiple variable assignment .参见例如: Linux Bash:多变量赋值。 Don't do this with binary input though: Is there a binary safe <<< in bash?
不过,不要使用二进制输入来执行此操作: bash 中是否有二进制安全的 <<<?
I use this in my .bash_profile, and it works beautifully.我在我的 .bash_profile 中使用了它,它运行良好。
if [ -n "$SSH_CONNECTION" ] ;
then
echo $SSH_CLIENT | awk '{print $1}'
fi
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;
}
If you prefer awk
:如果您更喜欢
awk
:
$ SSH_CLIENT="10.0.40.177 52335 22"
$ echo $SSH_CLIENT|awk '{print $1}' # first element
10.0.40.177
$ echo $SSH_CLIENT|awk '{print $2}' # second element
52335
$ echo $SSH_CLIENT|awk '{print $3}' # third element
22
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.