What do you someone breaks something? I post the solution here...

Kubernetes (K8s/K3d) / Terraform / Ansible / Linux / AWS / Docker / Bash / Python / ELK / CI/CD / Java / Traefik / Nginx / CentOs / Ubuntu


Bash Script to run a command on Multiple Servers

Use Case

A bash script that takes list of hostnames (comma separated) as an argument.
This script, when executed, connects to all the servers via. SSH (standard port) (assume password-less connectivity) and give a single prompt to the user. When the user executes a command on this prompt, the script runs the command on all connected servers and display the output.


Bash Script

#!/bin/bash

USER=<common-username-for-all-servers>
read -p "Enter the Command:" command
for host in $(tr ',' $'\n' <<< $1)
do
#echo $host
ssh -o StrictHostKeyChecking=no -i <ssh-key-path> $USER@$host $command
done

To use the above script user name and SSH Key for all the server should be same.

How to run the above script:

Lets assume that the script is saved as 'test.sh' in <some_path>, then the command syntax will be something like this: <some_path>/test.sh <host_name1>,<host_name2>,.........

Example: ./test.sh 192.0.0.1,10.0.0.1,10.0.0.2

No comments:

Powered by Blogger.