RockySAnand
RockySAnand

Reputation: 1

Pinging mutiple IP simultaneously using BASH

I have a shell script in which I am trying to simultaneously ping multiple IP's at the same time

#!/bin/sh

#-------------------------------
#Decleration of IP Address
#-------------------------------

IP_linux32='135.24.229.174'
IP_linux64='135.24.228.128'
IP_freeBSD32='135.24.228.104'
IP_freeBSD64='135.24.228.129'
DUMMY='135.24.229.0'

count_linux32=$( ping -c2 -i5 $IP_linux32 |grep icmp* ) &
count_linux64=$( ping -c2 -i5 $IP_linux64 |grep icmp* ) &
count_freeBSD32=$( ping -c2 -i5 $IP_freeBSD32 |grep icmp* ) &
count_freeBSD64=$( ping -c2 -i5 $IP_freeBSD64 |grep icmp* ) &
dummy=$( ping -c2 -i5 $DUMMY |grep icmp* ) &

sleep 6

if [[ ( "$count_linux32" -eq 0 && "$count_linux64" -eq 0 ) ]]
 then
        echo "Linux is up"
 else
        echo "Linux not up"
fi
if [[ ( "$count_freeBSD32" -eq 0  && "$count_freeBSD64" -eq 0 ) ]]
 then
        echo "BSD is up"
 else
        echo "BSD si not up"
fi
if [[ "$dummy" -eq 0 ]]
 then
        echo "Dummy is up"
 else
        echo "Dummy is not up"
fi

The Dummy is false IP which should fail according to the code but still I am getting "Dummy is up" and not "Dummy is not up".

Is there anything which I am doing wrong.

I tried referring to lot of solutions but still I am not able to figure it out

Upvotes: 0

Views: 2511

Answers (2)

OkieOth
OkieOth

Reputation: 3704

You can try nmap, but it also tests sequentially.

nmap -sP ADDR1 ADDR2 ADDR3

Upvotes: 0

Swami Moksha
Swami Moksha

Reputation: 486

Updated as per comment:

Make a list of your ips in a file, say, list.txt. It may look something like:

192.168.0.21
192.168.0.53
.
.
.
192.168.0.137

Then you may use the following script:

#!/bin/bash
# Program name: ping_all_ips.sh

date

cat /path/to/list.txt |  while read output
do
    ping -c 1 "$output" > /dev/null
    if [ $? -eq 0 ]; then
    echo "node $output is up" 
    else
    echo "node $output is down"
    fi
done

That will give you the status of your nodes. you may even store the result in a file ./ping_all_ips.sh > ping_log.txt or schedule the task using crontab.


For Simultaneous Pinging

As per recent comment


For the real simultaneous thing, you have to use languages that support multithreading like Cuda, I suppose. But for all practical purposes, the following code will tell you if all nodes are up or not.

#!/bin/bash
# Program name: ping_all_ips.sh

date

cat ip.txt | xargs -n 1 -I ^ -P 50 ping -c2 ^ > log.txt

if grep -q 'Unreachable' log.txt
then
  echo "All hosts are not up"
else
  echo "All hosts are up"
fi

Upvotes: 1

Related Questions