Bash for loop to ssh into multiple devices and run specific commands

bash
linux
tinkerboards

#1

Greetings,

I would appreciate any help/guidance in constructing an effective for loop with the ability to ssh into multiple devices and run specific commands on them. Since I am very new to bash scripting, other sites and the way that they are explaining things are getting kind of confusing. Hopefully someone can alleviate some of my confusion. So I have close to 100 machines (many of which are TinkerBoards but some that aren’t) that I need to be able to ssh into and then perform specific commands on. Right now I am a bit lost on where to start. The hostnames are conveniently coined “termX” where X represents a number from 1 to 100. As I stated above, not every terminal is a Tinkerboard so is this going to mess up the loop in some way? Help is appreciated.


#2

You can use something as follows:

for i in {1..5}
do
   echo "$i"
   echo "term${i}"
   echo "ssh -t user@term${i} -- command arg1"
done

For example run w command on 5 hosts named as term01, term02, term03, term04, and term05:

#!/bin/bash
user_name="vivek"
for i in {01..05}
do
     ssh -t ${user_name}@term${i} -- w
done

#3

Thank you so much, I think i get the hang of it. There are a couple other ways I discovered too! One thing I am still wondering about is how to make it so that I do not have to enter a password every time into the machine I am connecting to with ssh. Could you assist me with that as well? Thanks in advance!


#4

Set up ssh public and private key based authentication:

  1. How To Setup SSH Keys on a Linux / Unix System
  2. Linux / UNIX: Generate SSH Keys
  3. SSH Public Key Based Authentication on a Linux/Unix server