I need to Obtain my remote Linux Server eth1 IP address using bash script through the ssh and i have following command:
/sbin/ifconfig eth1 | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'
but when i run :
spawn ssh -t $user@$remote_host "/sbin/ifconfig eth1 | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $2}' ; echo $ip "
it says can't read "1": no such variable
while executing
"spawn ssh -t $user@$remote_host "ip=/sbin/ifconfig eth1 | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'
; echo $ip ""
(file "./ssh2.sh" line 11)
So could please help me with this issue.
Thanks
Best Answer
Why not use
ip
instead of the deprecatedifconfig
, and skip all the extra greps and cuts since awk can do that.So a command like
ip addr show dev eth0 | awk '/^ +inet / {split($2,a,"/"); print a[1]}'
In any case, most of your problem in your example commands have to do with the type of quotes you choose, and how bash evaluates them.
If you do something like
cfrancy@ws:~$ ssh root@srv01 echo "Hello $USER"
then the output you will see isHello cfrancy
, and notHello root
like you might expect. Because you have used double quotes"
around your command for the remote system, all the variables are evaluated before the command is sent. The commandcfrancy@ws:~$ ssh root@srv01 echo 'Hello $USER'
will returnHello root
since the$USER
is evaluated on the remote site. Of course you also need to switch around or escape your other quotes inside your compound command so things work out properly.Anyway, keeping the quoting behavior in mind the command would probably do what you want. though I think my solution that uses only
ip
, andawk
is a better choice since I am only useing 2 programs instead of 4.