Monday, March 13, 2006

Script: cluster_exec.sh

I just wrote a new bash script that is designed to streamline some fairly simple administration tasks and I thought I'd share it with everyone; cluster_exec.sh

It's far from perfect but it gets the job done. In my day to day tasks it's helpful to be able to execute a command on a series of servers one after the other, so that I can gather information, or reload a service, or whatever.

In the past I would either use SSH to connect directly to each box individually, run the command, and then move on to the next box. If it was really repetitive I might write a script that would do something similar to the one below, but it would be much less flexible.

The flexibility of this bash script is what sets it apart from writing job specific scripts every time you have a task that needs to be executed on let's say like 10 servers. I don't have to write any more of those, or at least I won't have to write large components of them in the future.

This script could be hacked to execute all these commands at the same time and it's pretty easy to integrate into other scripts. You can also use it with multiple clusters by defining the CLUSTER environment variable with a list of the servers you need to connect to.

It's really simple in it's design so it should work anywhere. It's been tested on Mac OS X 10.4 and Debian Linux.


#!/bin/bash

#
# execute a command via SSH on a cluster of servers.
#

# Setting the CLUSTER environment variable
#
# In bash, you would execute the following at the command line, as an
# example...
#
# CLUSTER="server1 server2 otheruser@server3 root@server4"
#
# And then;
#
# export CLUSTER
#
# Otherwise it will use the default file listed below..
CLUSTER_FILE=~/scripts/cluster_exec.data

##set up other variables;
if [ -x /usr/bin/sshas ]; then
SSH=/usr/bin/ssh;
else
SSH=`which ssh`;
fi

##Check for an argument.
if [ ! "$1" ]; then
echo "usage $0 \"\"";
echo "see script comments for CLUSTER variable description.";
exit 1;
fi

##If there is no CLUSTER env variable, define some data.
if [ ! $CLUSTER ]; then
CLUSTER=`cat $CLUSTER_FILE`;
fi

##Let's do it!!
for EXECUTE_ON in $CLUSTER
do
echo "EXECUTING ON $EXECUTE_ON: \"$1\"";
$SSH $EXECUTE_ON $1;
done



Technorati Tags: , ,

No comments:

Post a Comment