Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash script to ssh multiple servers in a Loop and issue commands

Tags:

bash

ssh

I have a text file in which I have a list of servers. I'm trying to read the server one by one from the file, SSH in the server and execute ls to see the directory contents. My loop runs just once when I run the SSH command, however, for SCP it runs for all servers in the text file and exits, I want the loop to run till the end of text file for SSH. Following is my bash script, how can I make it run for all the servers in the text file while doing SSH?

#!/bin/bash
while read line
do
    name=$line
    ssh abc_def@$line "hostname; ls;"
#   scp /home/zahaib/nodes/fpl_* abc_def@$line:/home/abc_def/
done < $1

I run the script as $ ./script.sh hostnames.txt

like image 888
Zahaib Akhtar Avatar asked Nov 27 '13 23:11

Zahaib Akhtar


2 Answers

A little more direct is to use the -n flag, which tells ssh not to read from standard input.

like image 51
Jack Avatar answered Sep 18 '22 06:09

Jack


Change your loop to a for loop:

for server in $(cat hostnames.txt); do
    # do your stuff here
done

It's not parallel ssh but it works.

like image 39
R.Sicart Avatar answered Sep 17 '22 06:09

R.Sicart