Friday, July 12, 2013

Asynchronous bash to run command in multiple remote hosts

I wanted to inspect the date in multiple servers to make sure ntpdate was running correctly. Here is how with runInHosts.sh a simple Plain Old Bash (POB) script.
#!/bin/bash -e
# runInHosts.sh
# @author: Nestor Urquiza
# @created: 20130712
USAGE="Usage: `basename $0` <clusterNodes[user@host space delimited list or a path to a file comntaining the list]> <command>"
if [ $# -ne "2" ]; then
echo $USAGE
exit 1
fi
function run() {
echo "$1: $(ssh $1 $2)"
}
clusterNodes=$1
command=$2
#If not a list then try path
if [[ ! "$clusterNodes" =~ ^.*@ ]]
then
if [ ! -f "$clusterNodes" ]
then
echo $USAGE
exit 1
fi
clusterNodes=`cat $clusterNodes`
fi
for host in $clusterNodes; do
run $host "$command" &
done
wait
view raw runInHosts.sh hosted with ❤ by GitHub
See below a typical response showing the asynchronous nature of this script
# pure command line
$ ./runInHosts.sh "user@server1.sample.com user@server2.sample.com user@server3.sample.com user@server4.sample.com user@server5.sample.com" date
user@server5.sample.com: Fri Jul 12 11:45:02 EDT 2013
user@server2.sample.com: Fri Jul 12 11:45:02 EDT 2013
user@server4.sample.com: Fri Jul 12 11:45:02 EDT 2013
user@server3.sample.com: Fri Jul 12 11:45:02 EDT 2013
user@server1.sample.com: Fri Jul 12 11:45:02 EDT 2013
# using a file
$ cat hosts.txt
user@server1.sample.com
user@server2.sample.com
user@server3.sample.com
user@server4.sample.com
user@server5.sample.com
$ ./runInHosts.sh hosts.txt date
user@server5.sample.com: Fri Jul 12 11:45:02 EDT 2013
user@server2.sample.com: Fri Jul 12 11:45:02 EDT 2013
user@server4.sample.com: Fri Jul 12 11:45:02 EDT 2013
user@server3.sample.com: Fri Jul 12 11:45:02 EDT 2013
user@server1.sample.com: Fri Jul 12 11:45:02 EDT 2013

No comments:

Followers