How to Run a Single Command on Multiple Linux Machines at Once

Image: Shutterstock

I’m always looking for ways to make my work more efficient, so the last thing I want to have to do is log into multiple Linux machines and run a single command on each. I would much rather have the ability to run this command on multiple machines at once.

SEE: 40+ open source and Linux terms you need to know (TechRepublic Premium)

Of course, there are apps for that. But since this is Linux, wouldn’t it make more sense to create your own solution? Of course it would. After all, Linux is about choice, power and flexibility.

Say, for example, you have multiple Ubuntu servers and you want to run sudo apt-get update and sudo apt-get upgrade on them all at the same time. You don’t need to log into each of these machines to run these commands, not when there are scripts to handle this task for you.

I found such a script and modified it so that you can use it to create multiple scripts for specific hosts (such as Ubuntu or RHEL based servers). Let’s take a look at this script and see how to make it work.

What you will need

To use this script, you will need a Linux machine to run the command and Linux servers to send commands to. Depending on the command you want to run on the remote servers, you will need a user with sudo privileges.

That’s it. Let’s do some magic.

How to configure SSH

The first thing we need to do is create an SSH configuration file that will define our remote hosts. But there is a trick to this particular setup. We will define hostnames starting with ubuntu- or rhel-, depending on the operating system of each.

On the system where you will run the script, create the SSH configuration file with the command:

nano ~/.ssh/config

Let’s say we have the following:

Ubuntu based systems on IP addresses 192.168.1.11 and 192.168.1.13 and RHEL based machine on IP address 192.168.1.14. Our configuration file might look like this:

Host rhel-db1

   Hostname 192.168.1.14

Host ubuntu-invoice
   Hostname 192.168.1.11

Host ubuntu-portainer
   Hostname 192.168.1.13

Save and close the file.

How to create the scenario

Now we will create two scripts, one for Ubuntu servers and one for RHEL servers. Create the Ubuntu server script with the command:

nano ~/ubuntu-cmd

In this file, paste the following:

!/bin/bash

# Get the user's input as command
[[ -z ${@} ]] && exit || CMD_EXEC="${@}"

# Get the hosts from ~/.ssh/config whose names are prefixed by `lan-`
HOSTS=$(grep -Po ‘HostsKubuntu-.*’ “$HOME/.ssh/config”)

# Test weather the input command uses sudo
if [[ $CMD_EXEC =~ ^sudo ]]
then
    # Ask for password
    read -sp '[sudo] password for remote_admin: ' password; echo

    # Rewrite the command
    CMD_EXEC=$(sed "s/^sudo/echo '$password' | sudo -S/"     "$CMD_EXEC")
fi

# loop over the hosts and execute the SSH command, remove `-a` to override the>
while IFS= read -r host
do
echo -e 'n