Wednesday, December 9, 2009

Quick tip: Deploying command on multiple servers (easy script)

When you maintain hundreds of server, A good sysadmin starts to design scripts that make his life easier. Let me show you what I do.

First make sure you have a file with a the list of server names or IPs.

#cat server.list

Second make sure you have setup ssh keys from your machine (user root) to all the machines on the list. This is the only part that can be complicated, however if you have deployed machines using a Kickstart server you can make sure that all the server on pools use the same auth keys on root directory.

Now you can create the script.

for i in `cat $1`
ssh -o ConnectTimeout=10 -o BatchMode=yes $i $2;

Very simple right. I will call it

Let me explain it really quick.
The script will take every line of file (IP or name) and it will ssh to that machine so it can run $2 (command).
The Option ConnectTimeout will guarantee that the ssh will try to connect for 10 seconds.
Batchmode will guarantee that no password will be asked so the ssh connection will pass.

Then you can use it ....

#./ server.list "/etc/init.d/apache restart"

Very helpful to restart apache on a Web server Farm.

Let's add something else to the script.

The script performs commands sequentially meaning that it has to wait until the command finishes to continue with the next server. But if you want to perform the command at the same time in all the servers we need to add the flag -f to the ssh command.


ssh -o ConnectTimeout=10 -o BatchMode=yes $i $2;


ssh -f -o ConnectTimeout=10 -o BatchMode=yes $i $2;


Enjoy it....

No comments:

Post a Comment