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


Copyright 2021. All rights reserved.

Posted March 25, 2022 by Timothy Conrad in category "Linux

About the Author

If I were to describe myself with one word it would be, creative. I am interested in almost everything which keeps me rather busy. Here you will find some of my technical musings. Securely email me using - PGP: 4CB8 91EB 0C0A A530 3BE9 6D76 B076 96F1 6135 0A1B