Steven
Steven

Reputation: 13

ssh to a list of servers and run a command against the same list

I have a list of servers where I want to ssh to each server in the list, then run a command against the same list of servers, before moving to the next server and running the command through the list again.

#!/bin/bash

while read -u 9 server; do
    ssh root@$server iperf -c $server -y C >> "/tmp/results.txt"
    done 9< /root/servers.txt

I would like the results to show

server1 -> server1
server1 -> server2
server1 -> server3
server2 -> server1
server2 -> server2
server2 -> server3

but the results show

server1 -> server1
server1 -> server2
server1 -> server3

EDIT

This is what I ended up with:

#!/bin/bash

SERVERS=`cat /root/servers.txt`
DATE=$(date +%Y%m%d_%H%M%S)

for server in $SERVERS; do
    echo "Starting iperf server on $server"
    ssh root@$server nohup iperf -s < /dev/null >> /tmp/log_$DATE.txt 2>&1 &
    sleep 5
    for client in $SERVERS; do
            echo Testing from $client to $server
            ssh root@$client iperf -c $server -y C >> /tmp/results_$DATE.txt
    done
    ssh root@$server pkill -KILL iperf >> /tmp/log_$DATE.txt
done

echo "Test results saved to /tmp/results_$DATE.txt" 

Upvotes: 1

Views: 1800

Answers (1)

KamilCuk
KamilCuk

Reputation: 140970

You want all possible 2 length permutations of list of servers. Then you want to run for each pair of servers the test. Nothing simpler.

while read -r srv1 srv2; do
    ssh root@"$srv1" iperf -c "$srv2" -y C >> "/tmp/results.txt"
done < <(
    while read -r line; do
        sed 's/$/ '"$line"'/' /root/servers.txt
    done < /root/servers.txt
)
  1. First the <( .. ) part. For each line in file the sed is run. The sed's adds the line to the end of the file and outputs it. Thus we get all possible pairs of servers.
  2. For each pair, tun the perf command.
  3. We can also do a | redirection.

while read -r line; do
     sed 's/$/ '"$line"'/' /root/servers.txt
done < /root/servers.txt |
while read -r srv1 srv2; do
    ssh root@"$srv1" iperf -c "$srv2" -y C >> "/tmp/results.txt"
done

Upvotes: 2

Related Questions