xargs - Run a command on lots of hosts

Run a command on lots of hosts

If you want to reboot lots of linux hosts, or maybe run updates, or anything else this will be helpful. It's also not exclusivly for running the same command on many machines, but with XARGS you can template commands to do anything - read the XARGS documentation for more information.

Instructions

vi hosts.txt
192.168.1.1
192.168.1.2
my.cool.hostname.local
vi myScript.sh
#!/bin/bash
cat hosts.txt | xargs -I HOST ssh-keyscan -H HOST >> ~/.ssh/known_hosts
cat hosts.txt | xargs -I HOST ssh root@HOST "reboot"

Replace reboot with whatever command (and arguments) you wish to run.

The ssh-keyscan line is to grab the signatures of each host and put them in the known_hosts file. If you don't do this and you haven't connected to one or more of the machines in hosts.txt before you will get the normal SSH warning where you have to type yes to connect to the new host.

chmod +x myScript.sh
./myScript.sh

Other examples

SCP file to multiple hosts

#!/bin/bash
cat hosts.txt | xargs -I HOST ssh-keyscan -H HOST >> ~/.ssh/known_hosts
cat hosts.txt | xargs -I HOST scp fileToCopy.bin root@HOST:/path/to/destination