Execute one command on all hosts

I have a couple of machines in my data center and sometimes it can be useful to run the same command on all the hosts.

For that purpose, I created a simple bash script that loops over a list of machine names and executes a command using ssh.

host1.example.com
host2.example.com
#!/usr/bin/env bash
KEY_SWITCH="-i ~/.ssh/custom_id_rsa"
USER="root"

function usage() {
        echo "Usage: exec_command.sh list \"command\""
        echo "     list      List type (linux, centos, debian)"
        echo "     command   Command to be executed on all hosts in the list"
}

if [ -z "$1" ]
then
        usage
        exit 1
fi
list_file="list_$1"

if [ ! -f "$list_file" ]
then
        echo "Error: Unable to find list file $list_file"
        echo
        usage
        exit 1
fi

echo "Using list file: $list_file"

if [ -z "$2" ]
then
        echo "Error: Command is not provided"
        echo
        usage
        exit 1
fi
command="$2"

IFS=$'\n' read -d '' -r -a hosts < $list_file
for host in "${hosts[@]}"
do
        echo "Executing command on host $host"
        echo
        ssh -q ${KEY_SWITCH} ${USER}@${host} "${command}"
        echo
        echo "Done executing on host $host"
done

As you can see the list is just a file named list_LISTNAME that contains one hostname per line.

I am using a custom key file for ssh to connect to my hosts, if that is not used change KEY_SWITCH value to "".

When the script is available and executable I can now run commands like:

$ ./execute_command.sh centos "yum update -y"
$ ./execute_command.sh debian "apt-get update && apt-get upgrade -y"
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s