Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SSH to multiple hosts at once

Tags:

ssh

I have a script which loops through a list of hosts, connecting to each of them with SSH using an RSA key, and then saving the output to a file on my local machine - this all works correctly. However, the commands to run on each server take a while (~30 minutes) and there are 10 servers. I would like to run the commands in parallel to save time, but can't seem to get it working. Here is the code as it is now (working):

for host in $HOSTS; do
    echo "Connecting to $host"..
    ssh -n -t -t $USER@$host "/data/reports/formatted_report.sh"
done

How can I speed this up?

like image 725
user3502260 Avatar asked Apr 06 '14 15:04

user3502260


People also ask

How do I open multiple SSH sessions?

Start Multiple SSH instances To start the multiple instances, right click on the remote node and select 'Start'. From the sub menu of 'Start' item, choose the number of instances you want to open.

How do I connect to multiple Linux servers?

To run commands on multiple servers, add the servers to a hosts file as explained before. Then run pdsh as shown; the flag -w is used to specify the hosts file, and -R is used to specify the remote command module (available remote command modules include ssh, rsh, exec, the default is rsh).


2 Answers

You should add & to the end of the ssh call, it will run on the background.

for host in $HOSTS; do
    echo "Connecting to $host"..
    ssh -n -t -t $USER@$host "/data/reports/formatted_report.sh" &
done
like image 161
Tomas Pastircak Avatar answered Sep 17 '22 20:09

Tomas Pastircak


I tried using & to send the SSH commands to the background, but I abandoned this because after the SSH commands are completed, the script performs some more commands on the output files, which need to have been created.

Using & made the script skip directly to those commands, which failed because the output files were not there yet. But then I learned about the wait command which waits for background commands to complete before continuing. Now this is my code which works:

for host in $HOSTS; do
    echo "Connecting to $host"..
    ssh -n -t -t $USER@$host "/data/reports/formatted_report.sh" &
done
wait
like image 22
user3502260 Avatar answered Sep 18 '22 20:09

user3502260