Bash – How to run select commands on multiple servers from a shell script

bashshellshell-scripting

How can I execute scripts from arguments on multiple servers?

I'm trying to build a command list, and then execute commands on each server. I'm unable to generate the command list in a way that can be eval'd correctly on each server.

Here's my entire script so far. Essentially I'd like to log into each server in the $server_array and execute either all of the commands in $script_arr or just the selected command.

#!/bin/bash

# run-commands.sh [optional script name]
# ex. run-commands.sh
# ex. run-commands.sh date_script
# ex. run-commands.sh hostname_script

# declare -a server_arr=("a.local" "b.local")
declare -a server_arr=("localhost")

if [ $# -eq 0 ]
  then
    # Default Processes
    declare -a script_arr=("date_script" "hostname_script")
else
    declare -a script_arr=($1)
fi

build_cmds()
{

    script_arr=("${@}")
    declare -a cmds

    for script_name in "${script_arr[@]}"
    do

        case "$script_name" in
            "date_script")
                cmds+='printf "executing date command\n; "'
                cmds+='date'
                cmds+='printf "date command executed\n; "'
            ;;
            "hostname_script")
                cmds+='printf "executing date command\n; "'
                cmds+='date'
                cmds+='printf "date command executed\n; "'
            ;;
        esac

    done

}

build_cmds "${script_arr[@]}"

for cmd in "${cmds[@]}"
do
    ssh user@$server_name -T 'eval "$cmd"'
done

echo "Completed executing all commands"

Best Answer

capistrano, mssh, and clusterssh are all tools that claim to issue commands to multiple servers at once. It's a complex enough task, as you found, that it's probably better not to reinvent the wheel.