Nelson
Nelson

Reputation: 3232

How can I ssh into a second server, run a command, and assign the output to a variable?

This is what I am attempting to do:

fromServer=$(ssh -A first.com ssh second.com rpm -qa | grep exampleString)
echo $fromServer

echo does not print anything. If I manually shh into first and then ssh into second then run the command I get output:

ssh first.com
ssh second.com
rpm -qa | grep exampleString

How can I combine these three steps into one line and store the output into a variable?

Upvotes: 0

Views: 175

Answers (1)

zmo
zmo

Reputation: 24812

Use proper quoting or escaping:

fromServer=$(ssh -A first.com 'ssh second.com rpm -qa | grep exampleString')
echo $fromServer

or

fromServer=$(ssh -A first.com ssh second.com rpm -qa \| grep exampleString)
echo $fromServer

% VAR=$(ssh -C user@server ls -la \| grep vim)
% echo $VAR
-rw-------  1 user user      15153 Mar  22 13:45 .vimrc

edit: oooooooh, sneaky, I did not see you were doing two SSH ☺

So then you'll need a bit more quoting, because you don't want to have your pipe being interpreted by first.com. Here's three ways to work around that:

fromServer=$(ssh -A first.com ssh second.com rpm -qa \\\| grep exampleString)
fromServer=$(ssh -A first.com 'ssh second.com rpm -qa \| grep exampleString')
fromServer=$("ssh -A first.com 'ssh second.com rpm -qa | grep exampleString'")

What's happening is that you want to execute:

user@second % rpm -qa | grep exampleString

on the second.com server, so you have to escape the pipe so it's not interpreted by the first.com server:

user@first % ssh second.com rpm -qa \| grep exampleString
or
user@first % ssh second.com 'rpm -qa | grep exampleString'

but then again, you need to have that executed on first.com, from your local workstation, as you still don't want to see the pipe interpreted, you need to add a second layer of escaping/quoting:

user@workstation % ssh first.com "ssh second.com 'rpm -qa | grep exampleString'"
or
user@workstation % ssh first.com 'ssh second.com rpm -qa \| grep exampleString'

and then, once you're sure you get an output you can put that whole command's output in a variable:

VAR=$(ssh first.com "ssh second.com 'rpm -qa | grep exampleString'")

HTH

Upvotes: 1

Related Questions