Skip to content

Instantly share code, notes, and snippets.

@Mohitsharma44
Created June 1, 2018 16:09
Show Gist options
  • Select an option

  • Save Mohitsharma44/a630a5ee6aa819c79f74873b37ae6d4d to your computer and use it in GitHub Desktop.

Select an option

Save Mohitsharma44/a630a5ee6aa819c79f74873b37ae6d4d to your computer and use it in GitHub Desktop.
Run a script on multiple servers in parallel
#!/bin/bash
if [ $# = 0 ]
then
self=`basename $0`
echo "Execute a command on multiple servers."
echo
echo "1. Basic Usage"
echo
echo " $self server1 [server2 ...] command"
echo
echo "2. Command"
echo
echo " Keep in mind that the command you want to run should be the last argument"
echo " and should be in single or double quotes."
echo
echo "3. Remote User"
echo
echo " The commands are ran as root. If you want to run them as another user, use:"
echo
echo " user=www-data $self server1 [server2 ...] command"
echo
echo "3. Common Domains"
echo
echo " If all servers are under the same domain, you can set a domain variable and"
echo " provide only the subdomain parts to the $self command, like so:"
echo
echo " domain=example.org $self s01 s02 s03 command"
echo
echo " The command will be run on s01.example.org, s02.example.org, and so on."
exit 1
fi
command="${@: -1}"
servers_count=$(($# - 1))
servers="${@:1:$servers_count}"
user=${user:-root}
if [ -n "$domain" ]
then
domain=".$domain"
else
domain=""
fi
if [ -z "$command" ]
then
echo "Please provide a command to run as the last argument (in quotes)."
exit 2
fi
if [ -z "$servers" ]
then
echo "Please provide at least one server name to run the command on."
exit 3
fi
echo "Running the following command on $servers_count server(s):"
echo
echo $command
echo
NPROC=servers_count
for server in $servers
do
((i=i%NPROC)); ((i++==0)) && wait
hostname="$server$domain"
echo "---> Running command on $hostname as $user:"
ssh $user@$hostname "$command" &
echo
done
@Mohitsharma44

Copy link
Copy Markdown
Author

Example:

user=pi bash runon 192.168.1.11 192.168.1.12 192.168.1.13 192.168.1.14 192.168.1.15 192.168.1.16 192.168.1.17 192.168.1.18 192.168.1.19 192.168.1.20 192.168.1.21 192.168.1.22 192.168.1.23 192.168.1.24 192.168.1.25 'pwomxplayer -A udp://239.0.1.23:1234?buffer_size=1200000B'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment