2010-02-09 10 views
8

$ SSH_CLIENT ha l'indirizzo IP con alcune informazioni di porta, e echo $ SSH_CLIENT mi dà '10 .0.40.177 52335 22' , ed esecuzione di

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

mi dà

  • 10.0.40.177

E vedo che il primo elemento è l'indirizzo IP.

Q: Come posso ottenere il primo elemento di $ SSH_CLIENT? $ {SSH_CLIENT [0]} non funziona.

risposta

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

o:

echo "${SSH_CLIENT%% *}" 
+2

Per l'all'oscuro (come me) il secondo sta facendo "sostituzione dei parametri". Ecco un riferimento: http://tldp.org/LDP/abs/html/parameter-substitution.html – notJim

8

è possibile utilizzare set -- esempio

$ 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 
0

si può ottenere modo programmatico tramite libreria 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; 
} 
0

Se preferite 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 
Problemi correlati