Bash scripting is fun and can help you automate a lot of things on your linux servers.
There are a lot of ways to run the same command on multiple servers. You can use pssh for example, bash scripts, python scripts, automation tools etc.
Here’s a simple bash script I wrote to execute the same command on multiple servers from a list. The list should contain one entry per line, either the server ip or hostname.
Create a file, name it server_list and add like 2 servers in that list.
Then download the bash script from my public GitHub repository: run-ssh-everywhere.sh
The script has some info at the begging so you can get used with the syntax, also prints help if no arguments are supplied.
If you run the script without any arguments, help is displayed:
Usage: ./run-ssh-everywhere.sh [-nsv] [-u USER] [-f FILE] COMMAND
Executes COMMAND as a single command on every server.
-f FILE Use FILE for the list of servers. Default: server_list.
-u USER Connect via ssh with the specifid user rather than localuser. Default: bogdan.
-p PASS Connect via SSH with the password provided as argument to the script. Default: .
-n Dry run mode. Display the COMMAND that would have been executed and exit.
-s Execute the COMMAND using sudo on the remote server.
-v Verbose mode. Displays the server name before executing COMMAND.
Some usage examples:
To find uptime:
By default the script will connect to the servers via SSH using the current user executing the script. If you want to use a specific user, then the command will become:
./run-ssh-everywhere.sh -u ssh_user "uptime"
Ideally you should have a public ssh key which is saved to the remote servers, otherwise you will be prompted to enter password for each of the servers.
If for example you have an use on multiple server and that user has the same password then you can use it like this:
./run-ssh-everywhere.sh -u ssh_user -p ssh_password "uptime"
If you want to run a command and pipe some arguments to it:
./run-ssh-everywhere.sh "rpm -qa | grep kernel"