9

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

2
  • take a look at code.google.com/p/parallel-ssh Commented Nov 27, 2013 at 23:12
  • 1
    @D.Shawley, I'm aware of parallel-ssh. I was wondering if this can be done using simple SSH! Commented Nov 27, 2013 at 23:15

4 Answers 4

18

The problem with this code is that ssh starts reading data from stdin, which you intended for read line. You can tell ssh to read from something else instead, like /dev/null, to avoid eating all the other hostnames.

#!/bin/bash
while read line
do
    ssh abc_def@"$line" "hostname; ls;" < /dev/null
done < "$1"
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, this works great! could you elaborate on why SSH starts reading stdin data? Thanks.
ssh reads stdin and sends it to the remote server to let you interact with remote programs. It doesn't know that hostname; ls; will just ignore that data.
9

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

Comments

3

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.

Comments

3

I open-sourced a command line tool called Overcast to make this sort of thing easier.

First you import your servers:

overcast import server.01 --ip=1.1.1.1 --ssh-key=/path/to/key
overcast import server.02 --ip=1.1.1.2 --ssh-key=/path/to/key

Once that's done you can run commands across them using wildcards, like so:

overcast run server.* hostname "ls -Al" ./scriptfile
overcast push server.* /home/zahaib/nodes/fpl_* /home/abc_def/

1 Comment

Thanks for making this available, still have to explore it, looks pretty neat!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.