开发者

using a variable in a BASH command?

I have 20 machines, each running a process. The machines are named:

["machine1", "machine2", ...., "machine20"]

To inspect how the process is doing on machine1, I issue the following command from a remote machine:

ssh machine1 cat log.txt

For machine2, I issue the following command:

ssh machine2 cat log.txt

Similarly, for machine20, I issue the following command:

开发者_如何学JAVA
ssh machine20 cat log.txt

Is there a bash command that will allow me to view the output from all machines using one command?


If the machines are nicely numbered like in your example:

for i in {1..20} ; do ssh machine$i cat log.txt; done

If you have the list of machines in a file, you can use:

cat machinesList.txt | xargs -i ssh {} cat log.txt


You could store all your machine names in an array or text file, and loop through it.

declare -a machineList=('host1' 'host2' 'otherHost') # and more...


for machine in ${machineList[@]}
do
    ssh $machine cat log.txt
done

I assume your machines aren't literally named 'machine1', 'machine2', etc.

Some links:

  • bash Array Tutorial
  • GNU Bash Array Documentation


for i in {1..20}
do
   ssh machine$i cat log.txt
done


Use a loop?

for i in {1..20}
do
   ssh machine$i cat log.txt
done

But note that you're running cat within a remote shell session, not the current one, so this might not quite work as you expect. Try it and see.


Put your hosts in a file and use a while loop as shown below. Note the use of the -n flag on ssh:

while read host; do ssh -n $host cat log.txt; done < hosts-file

Alternatively you can use PSSH:

pssh -h hosts-file -i "cat log.txt"


I would recommend using a program called Shmux. Despite the name, it works really well. I've used it with more than 100 machines with good results. It also gracefully handles machine failures for you which could be a disadvantage with a bash for loop approach.

I think the coolest thing about this program is the ability to issue multiple threads for your commands which allows to run the commands on all 20 machines in parallel.


Aside from the suggestions for using a loop, you might want to take a look at tools, like pssh or dsh, designed for running commands on multiple clients.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜