Aaron
Aaron

Reputation: 3325

Ping hundreds in one script

I want to ping some servers on a game, they are all in the same format, only there are possibly hundreds of them. This is what I currently use:

ping server1.servername.com -n 20 | grep Minimum | awk '{print $3}' | sed s/,// >> Output.txt

That will ping the server 20 times, and chop off everything but the minimum ping amount. If I wanted to ping 300 of these servers, I would have to paste that same line 300 times... Is it possible to have it specify just something like 1-300 in one line without needing 300 lines of the same thing?

Upvotes: 1

Views: 1295

Answers (3)

rojo
rojo

Reputation: 24466

rojo@aspire:~$ help for

<snip...>

for ((: for (( exp1; exp2; exp3 )); do COMMANDS; done
    Arithmetic for loop.

    Equivalent to
        (( EXP1 ))
        while (( EXP2 )); do
            COMMANDS
            (( EXP3 ))
        done
    EXP1, EXP2, and EXP3 are arithmetic expressions.  If any expression is
    omitted, it behaves as if it evaluates to 1.

Try something like this:

for (( x=1; $x<=300; x++ )); do ( ping server$x.servername.com -n 20 | grep Minimum | awk '{print $3}' | sed s/,// >> Output.txt ); done

Update:

Here's the hackish idea I mentioned in my comments to this answer below. Caveat: I think my ping command must be different from yours. I'm composing this idea on a Debian machine.

Instead of -n count my ping syntax is -c count, and instead of a line containing "Minimum" I have "min/avg/max/mdev". So you might need to play with the grep syntax and so on. Anyway, with that in mind, modify the following as needed to perform a ping of each server in sequence from 1 to whatever until error.

#!/bin/bash
i=0
while [ $? -eq 0 ] && i=$(( i + 1 )); do (
        echo -n "server$i min: "
        ping server$i.servername.com -c 20 -i 0.2 | grep -P -o -e '(?<=\= )\d\.\d+'
); done
echo "n/a"

Basically in plain English, that means while exit code = 0 and increment i, echo the server name without a line break and ping it 20 times at 200ms interval, completing the echoed line with (scraping from the ping results) a decimal number preceded by an equal-space. (That pattern matches the minimum ping time result in the summary for Linux iputils ping.) If the ping fails, exit code will not equal 0 and the loop will break.

Upvotes: 2

emallove
emallove

Reputation: 1567

Sounds like a job for xargs, e.g.,

$ cat server-list | xargs -I% ping % -n 20 ...

Upvotes: 2

fedorqui
fedorqui

Reputation: 289495

You can use loops:

while read line
do
    ping $line.servername.com -n 20 | grep Minimum | awk '{print $3}' | sed s/,// >> Output.txt
done < servers_list

Upvotes: 2

Related Questions