March
25
Linux: Using ssh to run a script on multiple servers
To start, it will be more convenient if you have ssh keys setup on the servers. Otherwise you will be entering a password for each server you need to connect to.
To break this out create three files:
1. iplist.txt
2. checkservers
3. serverscript
* If your command is small enough you do not need to have a seperate serverscript file. I find it easier to put more complex scripts in their own file which is what the following example reflects.
Add your server IPs to iplist.txt:
192.168.1.10
192.168.1.22
192.168.1.45
192.168.1.100
Add you loop connection syntax in checkservers:
#!/bin/bash
for server in $(cat iplist.txt); do
ssh username@$server -i usernameprivatekeyfile 'bash -s' < serverscript >> server-results.txt
done
Add your script to serverscript:
#!/bin/bash
sudo -i
hostname
your
script
here
Final steps:
chmod 744 checkservers
chmod 744 serverscript
Finally run ./checkservers