Script to Send Mass Commands to Multiple Servers

One of the daily tasks as a System Engineer is to send mass commands to multiple servers a cross the fleet, like to yum update the system or just to check the server uptime, to give a couple of examples.
So, It’s important to know that there are many ways to accomplish this, for example using the tools like DSH (Distributed Shell), PSSH (Parallel SSH) or just writing your own Linux Bash Script for sending a command to multiple servers.
In the code down below, I present to you my basic bash script for looping through a list of servers, to send a command and print the output, it’s simple and it works like a charm.
Because of it’s simplicity, It should be self explanatory, but just in case, I added a few comments to make it more clear for you.
The Mass Commands Script Code
#!/bin/bash #Script name: masscmd.sh #Author: LinuxAdminGeeks.com #Date 22/03/2021 #Sends a command to a list of servers #Requires 1 ip/host per line in the server list and the command to be sent #For example: ./masscmd mylist uptime #server list file name serverlist=$1 cmd=$2 #Validate the input server list name if [ "$*" == "" ]; then echo "Requires a serverlist and command: ./masscmd.sh serverlist command"; echo "for multiple commands use quotes and ; example: \"command1; command2; command3\" "; exit 1 fi #For Loop through the server list for server in $(cat $serverlist); do cmdres="$(ssh -qt $USER@$server "$cmd")"; echo -e "$server $cmdres"; done
You will be prompted for the user password, on every server, if you don’t have a passwordless access or your SSH KEY installed, you can learn about installing your ssh keys on my tutorial, just click on this link.
The Mass Commands Script uses the current $user that runs the script to login into the remote server, if you need to change it, feel free to modify my Mass Command Linux Bash Script to match your needs.
The Conclusion
There are many ways for sending mass commands to remote Linux servers, they offer you different capabilities like PSSH that is able to use multiple threads to agilize the process, it’s on to you to choose your prefer method.
If you to want learn more about this tutorial or have any questions, feel free to send your comments down below.
Don’t forget to check our other Tutorials, we are constantly submitting new ones every week.
Tags: for loop bash, linux bash scripts, mass command bash script, send a command to multiple servers