Solved

Shell script - run command using variable from a list

Posted on 2016-09-26
2
92 Views
Last Modified: 2016-09-26
Hi,

I need to issue a command to 10 hosts remotely and I was wondering what would be the best way to script it so I wouldnt have run it over and over for each one of them...

I was thinking on having a host list variable in a script and use:

ssh $HOST <command>

For each command I run I need to create a output file in the local machine where Im issuing the command from...

So it would be: ssh $HOST1 <command> > HOST1, ssh $HOST2 <command> > HOST2.. and so on....

What would be the best way to do it in a shell script?

Tks
0
Comment
Question by:joaotelles
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
2 Comments
 
LVL 68

Accepted Solution

by:
woolmilkporc earned 500 total points
ID: 41816267
You should create a file (e. g. "hostlist") containing your host names, one name per line.

Then use a "while" loop:

while read HOST
  do
     ssh -n  $HOST <command> > ${HOST}.result
   done < hostlist

Please note the "-n" flag of "ssh". It's very important here to prevent "ssh" from emptying stdin.
Note, too, that this doesn't work when "ssh" has to ask for a passphrase.
If you can't avoid this please let me know - we'll use a different approach then.
0
 
LVL 68

Expert Comment

by:woolmilkporc
ID: 41816276
If you don't have passwordless access to your hosts use "for" instead of "while" ("for" does not read from stdin):

for HOST in $(<hostlist)
  do
     ssh $HOST <command> > ${HOST}.result
   done
0

Featured Post

Enroll in July's Course of the Month

July's Course of the Month is now available! Enroll to learn HTML5 and prepare for certification. It's free for Premium Members, Team Accounts, and Qualified Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

SSH (Secure Shell) - Tips and Tricks As you all know SSH(Secure Shell) is a network protocol, which we use to access/transfer files securely between two networked devices. SSH was actually designed as a replacement for insecure protocols that sen…
Fine Tune your automatic Updates for Ubuntu / Debian
Learn how to find files with the shell using the find and locate commands. Use locate to find a needle in a haystack.: With locate, check if the file still exists.: Use find to get the actual location of the file.:
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
Suggested Courses

628 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question