$SSH_CLIENT has IP address with some port info, and echo $SSH_CLIENT gives me '10.0.40.177 52335 22', and Running
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.
Q : How can I get the first element of $SSH_CLIENT? ${SSH_CLIENT[0]} doesn't work.
sshvars=($SSH_CLIENT)
echo "${sshvars[0]}"
or:
echo "${SSH_CLIENT%% *}"
you can use set --
eg
$ 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 . Don't do this with binary input though: Is there a binary safe <<< in bash?
I use this in my .bash_profile, and it works beautifully.
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 )
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
:
$ 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.