比如現在需要對172.16.50.0/24網段的ip進行檢查,檢查哪些ip現在被佔用,哪些ip沒有被佔用,可以通過ping命令來檢查,指令碼如下:
[root@uatdns01 opt]# vim /opt/ping.sh #!/bin/bash . /etc/init.d/functions for var in {1..254}; do ip=172.16.50.$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]# chmod 755 /opt/ping.sh [root@uatdns01 opt]# sh /opt/ping.sh 172.16.50.1 [ OK ] 172.16.50.2 [FAILED] 172.16.50.3 [FAILED] 172.16.50.4 [FAILED] 172.16.50.5 [FAILED] ......... ......... 172.16.50.99 [ OK ] 172.16.50.100 [ OK ] 172.16.50.101 [ OK ] 172.16.50.102 [ OK ] 172.16.50.103 [ OK ] 172.16.50.104 [ OK ] 172.16.50.105 [ OK ] 172.16.50.106 [ OK ] 172.16.50.107 [ OK ] 172.16.50.108 [ OK ] 172.16.50.109 [ OK ] 172.16.50.110 [ OK ] 172.16.50.111 [FAILED] 172.16.50.112 [ OK ]
獲取172.16.60.0/24網段可用ip的shell指令碼 [root@ansible-server ~]# cat ip_ping.sh #!/bin/bash ip=1 while [ $ip != "254" ]; do ping 172.16.60.$ip -c 2 | grep -q "ttl=" && echo "172.16.60.$ip yes" || echo "172.16.60.$ip no" ip=`expr "$ip" "+" "1"` done 執行: [root@ansible-server ~]# sh ip_ping.sh 172.16.60.1 yes 172.16.60.2 no 172.16.60.3 no ............. 172.16.60.24 yes 172.16.60.25 yes 172.16.60.26 no ............. 如果只列印可用ip, 則指令碼修改如下: [root@ansible-server ~]# cat ip_ping.sh #!/bin/bash ip=1 while [ $ip != "254" ]; do ping 172.16.60.$ip -c 2 | grep -q "ttl=" && echo "172.16.60.$ip yes" || echo "172.16.60.$ip no" >/dev/null 2>&1 ip=`expr "$ip" "+" "1"` done 執行: [root@ansible-server ~]# sh ip_ping.sh 172.16.60.1 yes 172.16.60.21 yes 172.16.60.22 yes 172.16.60.23 yes 172.16.60.24 yes 172.16.60.25 yes 172.16.60.31 yes 172.16.60.32 yes 172.16.60.33 yes 172.16.60.34 yes 172.16.60.35 yes 172.16.60.36 yes 172.16.60.37 yes 172.16.60.38 yes 172.16.60.39 yes 獲取172.16.50.0/24, 172.16.51.0/24, 172.16.60.0/24 三個網段的可用ip [root@ansible-server ~]# cat ip_ping.sh #!/bin/bash ip=1 while [ $ip != "254" ]; do ping 172.16.50.$ip -c 2 | grep -q "ttl=" && echo "172.16.50.$ip yes" || echo "172.16.50.$ip no" >/dev/null 2>&1 ip=`expr "$ip" "+" "1"` ping 172.16.51.$ip -c 2 | grep -q "ttl=" && echo "172.16.51.$ip yes" || echo "172.16.51.$ip no" >/dev/null 2>&1 ip=`expr "$ip" "+" "1"` ping 172.16.60.$ip -c 2 | grep -q "ttl=" && echo "172.16.60.$ip yes" || echo "172.16.60.$ip no" >/dev/null 2>&1 ip=`expr "$ip" "+" "1"` done 執行: [root@ansible-server ~]# sh ip_ping.sh 172.16.50.1 yes 172.16.51.11 yes 172.16.50.16 yes 172.16.50.19 yes 172.16.51.20 yes 172.16.60.21 yes 172.16.50.22 yes 172.16.60.24 yes 172.16.50.25 yes 172.16.50.31 yes 172.16.60.33 yes 172.16.51.35 yes 172.16.60.36 yes 172.16.60.39 yes 172.16.51.41 yes 172.16.51.44 yes 172.16.50.52 yes 172.16.51.53 yes 172.16.50.55 yes 172.16.50.58 yes 172.16.51.65 yes ..................