Linux下批量ping某个网段的脚本

比如现在需要对192.168.0.0/24网段的ip进行检查,检查哪些ip现在被占用,哪些ip没有被占用,可以通过ping命令来检查,也可以通过nmap接参数来检查

ping命令脚本如下:

[root@ZFVM-APP-0-172 shell]# vim ping.sh
#!/bin/bash
. /etc/init.d/functions
for var in {1..254};
do
ip=192.168.0.$var
ping -c2 $ip >/dev/null 2>&1
if [ $? = 0 ];then
action "$ip" /bin/true
else
action "$ip" /bin/false
fi
done
 
[root@uatdns01 opt]# bash ping.sh
172.168.0.1                                                [FAILED]
172.168.0.2                                                [FAILED]
172.168.0.3                                                [FAILED]
172.168.0.4                                                [FAILED]
172.168.0.5                                                [FAILED]
.........
.........
192.168.0.249                                              [FAILED]
192.168.0.250                                              [FAILED]
192.168.0.251                                              [FAILED]
192.168.0.252                                              [FAILED]
192.168.0.253                                              [FAILED]
192.168.0.254                                              [FAILED]

用nmap需要先安装nmap命令

[root@ZFVM-APP-0-172 shell]# yum install -y nmap

[root@ZFVM-APP-0-172 shell]# nmap -v -sP 192.168.0.0/24 |grep down
Nmap scan report for 192.168.0.0 [host down]
Nmap scan report for 192.168.0.2 [host down]
Nmap scan report for 192.168.0.3 [host down]
Nmap scan report for 192.168.0.4 [host down]
Nmap scan report for 192.168.0.5 [host down]
......
......
Nmap scan report for 192.168.0.251 [host down]
Nmap scan report for 192.168.0.252 [host down]
Nmap scan report for 192.168.0.253 [host down]
Nmap scan report for 192.168.0.254 [host down]
Nmap scan report for 192.168.0.255 [host down]

 检查192.168.0.1网关是否可达的脚本

[root@ZFVM-APP-0-161 shells]# vim ping.sh 
#!/bin/bash
ping www.baidu.com -c 4 -W 5 > /dev/null 2>&1
if [ $? -eq 0 ]
then
  echo "网络已通"
else
  echo "网络不可达"
fi

执行结果

[root@ZFVM-APP-0-161 shells]# sh ping.sh 
网络可通