Passing a variable to an remote host with SSH

Posted by Dark Training on September 29, 2010 tags: | linux

Lets say that you need to pass a variable name from a script to remote hosts when you are using the SSH command inside of linux. A working example of this would be if you wanted to add a user to multiple machines.

If you tried to do this the way you normally send commands:

ssh user@machine 'command $var';

That would fail, the reason is you need to use double quotes when you are passing a variable from a script. Below I'll show an example where we get user input and define that as a variable to be used in the command I want run on each machine.

#!/bin/sh
echo "What is the user name to be added to all machines:"
read usern
for i in $(seq 1 16);
 do
  <p class="indented">echo "running /usr/sbin/adduser -m $usern; on machine $i"
  ssh root@machine$i "/usr/sbin/adduser -m $usern"</p>
done

In this case, all the machines are named "machine" and then a number. So we loop over the total number of machines with the variable "$i" and we take the user input "$usern" and send that to each machine.