Search code examples
awksshhostname

Adding the hostname of a remote server to a formatted ssh command response


If i run this command directly (via ssh terminal) on a remote REHL server: w -uh | awk -vhostname="$(hostname)" '{print "On "hostname ,$1,"is connected with IP: "$3}'

I get an output like this:

On remote.server1.address.com accountname is connected with IP: 8.8.8.8

However if i run this command remotely via SSH commands in a script (to check multiple servers): ssh account@remote.server.address.com w -uh | awk -vhostname="$(hostname)" '{print "On "hostname ,$1,"is connected with IP: "$3}'

The result of the command gives the local machine hostname instead of the remote server:

On local.machine.address.com accountname is connected with IP: 8.8.8.8

On local.machine.address.com accountname is connected with IP: 0.0.0.0

On local.machine.address.com accountname is connected with IP:255.255.255.255*

I'm looking for a result like below.

On remote.server1.address.com accountname is connected with IP: 8.8.8.8

On remote.server2.address.com accountname is connected with IP: 0.0.0.0

On remote.server3.address.com accountname is connected with IP:255.255.255.255*


Solution

  • It is happening because the command hostname is running on your local machine. You need to pass the entire command in quotes like:

    ssh account@remote.server.address.com "w -uh | awk -v hostname=\$(hostname) '{print \"On \"hostname ,\$1,\"is connected with IP: \"\$3}'"