Link to home
Start Free TrialLog in
Avatar of ittechlab
ittechlabFlag for Canada

asked on

Shell script - remote execution on multiple servers

I need to write a shell script to login to 5 linux servers using ssh and run a command remotely.

ssh keys are already.  key less authentication is setup already.
Avatar of noci
noci

for sys in systemname1 systemname2 systemname3 systemname4 systemname5 
do
     ssh ${sys} do_command
done

Open in new window


or with systemnames from a file:

for sys in $( cat systemnamefile )
do
     ssh ${sys} do_command
done

Open in new window

If your commands will take a long time to run, you can use one of the many parallel ssh wrappers or...

Just append an & to the end of do_command above.
If working from an X workplace, try clusterssh to run one command on many systems.
Avatar of ittechlab

ASKER

is below statement will work?

for sys in systemname1 systemname2 systemname3 systemname4 systemname5
do
     ssh ${sys}  "rpm -qa | grep httpd"
done
The syntax looks fine and when I run something similar, it works as expected. Please don't award me any points. They should be given to noci as it is their answer.
for sys in systemname1 systemname2 systemname3 systemname4 systemname5 
do
     ssh ${sys}  bash -c  "rpm -qa | grep httpd"
done

Open in new window


definitely will work as expected. (the | will need to be executed on the remte system ==>  it needs to be expanded on a command line on the remote system.
bash -c will do just that.
Having tested your original, noci, using the quotes works for me on my distro as well, without explicitly using bash.
@martyn, openssh does that, but not all ssh = openssh.  I do know of one that doesn't do /bin/sh -c...  (openvms)

Also the default shell of the user is taken from the password file if that is a menu or /bin/false there will be problems anyway.
@noci, thanks for the clarification. I imagined that there was a good reason for mentioning it specifically.
dssh handles it quite nicely

@noci, whatever menu or shell configured on the remote system is bypasssed when you pass a command to run. which is why setting /bin/false as the shell for user that should not be able to login does not work.

passing arguments white spaces or complex commands to ssh tend to be a total pain in pretty much all cases

if those are needed, you may resort to the easier

ssh destination sh -s <<EOF
set "$@"
# shell commands here
EOF
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.