BLOGROLLS

How I do stuff on all servers at once ..

By: Simon Quantrill On: Tue 13 January 2015
In: Unknown
Tags:
quantrill@amos:~/bin
$ cat all_hosts
#!/bin/bash
#This Script allows you to create a list of hosts 
#and run a command line on each host in the list.
#
#
#./all_hosts.sh "command;command2;" hostgroup
#./all_hosts.sh ls workstations 
#./all_hosts.sh ls dmzservers 
#./all_hosts.sh ls lanservers
#
#
# Directory containing host group file(s)
host_dir="$HOME/etc/hosts/"

# Check for required arguments
[ $# -gt 1 ] || {
echo "usage: $0 \"command(s)\" hostgroup ..." >&2
exit 1
}
# Take the command(s) off of the parameter stack
cmd="$1"
shift

# Place full paths to each hostfile in $hostfiles
# This will loop once for every (remaining) argument
for hostfile ; do
if [ -r "$host_dir/$hostfile" ] ; then
hostfiles="$hostfiles $host_dir/$hostfile"
else
echo "INVALID GROUP: $hostfile" >&2
fi
done

# Make sure we actually have hosts to operate on

[ -n "$hostfiles" ] || exit 1
#echo "hostfile " $hostfile
#echo "hostfiles" $hostfiles
# Execute the command(s) on each host
#sort $hostfiles | uniq | while read host; 
for host in `sort $hostfiles | uniq`;
do 
echo "*"
echo " **** ${host} ****" 
echo "*"
ssh "$host" "$cmd" || {
echo "ERROR: Couldnt execute $cmd on $host!" >&2
}
done

#for host in $hostfiles; do
#for host in $hostfiles; do
# echo $host;
# ssh "$host" "$cmd" || {
# echo "ERROR: Could not execute $cmd on $host!" >&2
# }
#done
quantrill@amos:~/etc/hosts
$ ls
dmzservers lanservers test workstations
$ cat dmzservers 
mail
apollo
hubble
galileo
cassini
soyuz
meteor
aura
mir
kvant
spectr
vela
freja
bion

now if I want to do something on all hosts I do this

$ ./all_hosts "ps -ef | grep ava" dmzservers
*
**** apollo ****
*
quantrill@apollo's password: 
1003 21062 21061 0 13:00 ? 00:00:00 bash -c ps -ef | grep ava
1003 21069 21062 0 13:00 ? 00:00:00 grep ava
*
**** aura ****
*
root 3721 1 0 Feb06 ?
# The next line is on line, but screws the layout of the wiki
00:00:11 /usr/local/bin/jvm/java1.4/1.4/bin/java -Xrs -cp ./lib/m11.jar:./lib/collections.jar:
./lib/jsdk.jar:./comp/AAOL.jar:
./comp/CommandFileRunner.jar:
./comp/EventLogger.jar:
./comp/http.jar:
./comp/Notifier.jar:
./comp/Omaha.jar:
./comp/PowerSourceAggregator.jar:
./comp/PSAggregator.jar:
./comp/RunTimeVerifier.jar:
./comp/Shutdowner.jar:
./comp/StdPowerSource.jar:
./comp/ps/StdPowerSource.jar:
./comp/shutdownerlets/OSshutdownerlet.jar:
com.apcc.m11.arch.application.Application

If you found the article helpful, please share or cite the article, and spread the word:


For any feedback or corrections, please write in to: Simon Quantrill