run a single command on multiple Linux machines at once

#Introduction

In this tutorial, How to run a single command on multiple Linux machines at once. I will create a script on the Linux servers to send commands to multiple servers.

Prerequisites

  • 2 Virtual Machine
  • ssh Connectivity Between 2 Servers

Configure SSH on Server 1

For example, The Server calls the name controller. This server is using the operating system Ubuntu.

create the SSH config file with the command:

cat ~/.ssh/config

For example, the content as output below

image 8

Create the script to run a single command on multiple Linux machines at once

We will create 1 script to run a command for a remote Linux server.

sudo vi /usr/local/bin/script_node1

In that file, paste the following:

#!/bin/bash

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

# Get the hosts from ~/.ssh/config
HOSTS=$(grep -Po 'Host\s\Knode1' "$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\033[1;33m'"HOST: ${host}"'\033[0m'
   ssh -n "$host" "$CMD_EXEC 2>&1" | tee -a "/tmp/$(basename "${0}").${host}"
done <<< "$HOSTS"

Save and close the file.

Now, We will update the package for server calls name node1 as command below:

script_node1 sudo apt-get update
run a single command on multiple Linux machines at once

Via youtube

Conclusion

You have run a single command on multiple Linux machines at once. I hope will this your helpful. Thank you for reading the DevopsRoles page!

,

About HuuPV

My name is Huu. I love technology and especially Devops Skill such as Docker, vagrant, git so forth. I likes open-sources. so I created DevopsRoles.com site to share the knowledge that I have learned. My Job: IT system administrator. Hobbies: summoners war game, gossip.
View all posts by HuuPV →

Leave a Reply

Your email address will not be published.

Comment moderation is enabled. Your comment may take some time to appear.

This site uses Akismet to reduce spam. Learn how your comment data is processed.