使用BASH同时ping多个IP

时间:2016-03-08 10:28:59

标签: multithreading bash shell ping

我有一个shell脚本,我试图同时ping多个IP

#!/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

Dummy是假IP,根据代码应该失败,但我仍然得到“Dummy is up”而不是“Dummy is not up”。

我做错了什么。

我尝试过很多解决方案,但我仍然无法弄清楚

2 个答案:

答案 0 :(得分:1)

根据评论更新:

在文件中列出您的ips,例如list.txt。它可能看起来像:

192.168.0.21
192.168.0.53
.
.
.
192.168.0.137

然后您可以使用以下脚本:

#!/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

这将为您提供节点的状态。您甚至可以将结果存储在文件./ping_all_ips.sh > ping_log.txt中,或使用crontab计划任务。

同时Ping?

根据最近的评论

对于真正的同时发生的事情,我想你必须使用支持multithreading的语言,例如Cuda。但是出于所有实际目的,以下代码将告诉您所有节点是否已启动。

#!/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

答案 1 :(得分:0)

您可以尝试nmap,但它也会按顺序进行测试。

nmap -sP ADDR1 ADDR2 ADDR3
相关问题