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:

Add you loop connection syntax in checkservers:
for server in $(cat iplist.txt); do

ssh username@$server -i usernameprivatekeyfile 'bash -s'  < serverscript  >> server-results.txt


Add your script to serverscript:

sudo -i



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