Solved

Shell script - run command using variable from a list

Posted on 2016-09-26
2
65 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
  • 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

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

Question has a verified solution.

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

Suggested Solutions

Utilizing an array to gracefully append to a list of EmailAddresses
Google Drive is extremely cheap offsite storage, and it's even possible to get extra storage for free for two years.  You can use the free account 15GB, and if you have an Android device..when you install Google Drive for the first time it will give…
Learn how to navigate the file tree with the shell. Use pwd to print the current working directory: Use ls to list a directory's contents: Use cd to change to a new directory: Use wildcards instead of typing out long directory names: Use ../ to move…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

776 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