需求:对192.168.200.0/24网段的ip进行检查,检查哪些ip现在被占用,哪些没有被占用,可以通过ping命令来检查,脚本如下:
[root@master ~]# cat ip_check.sh
#!/bin/bash
#sehn
. /etc/init.d/functions
for i in {1..254};
do
ip=192.168.200.$i
ping -c2 $ip > /dev/null 2>&1
if [ $? -eq 0 ]; then
action "$ip" /bin/true
else
action "$ip" /bin/false
fi
done
执行,因为数量太多我这里直接另起一个终端将其kill掉了
使用ps -ef找到执行脚本的进程,kill掉就行
[root@master ~]# ps -ef
...
root 93882 78742 0 19:26 pts/1 00:00:00 sh ip_check.sh
...
[root@master ~]# kill -9 93882
[root@master ~]# sh ip_check.sh
192.168.200.1 [FAILED]
192.168.200.2 [ OK ]
192.168.200.3 [FAILED]
192.168.200.4 [FAILED]
192.168.200.5 [FAILED]
192.168.200.6 [FAILED]
192.168.200.7 [FAILED]
192.168.200.8 [FAILED]
192.168.200.9 [FAILED]
192.168.200.10 [FAILED]
192.168.200.11 [FAILED]
192.168.200.12 [FAILED]
Killed
[root@master ~]#
显示该网段可用ip,脚本如下
[root@master ~]# cat ip_usable.sh
#!/bin/bash
#sehn
ip=1
while [ $ip -ne "254" ]; do
ping 192.168.200.$ip -c 2 | grep -q "ttl=" && echo "192.168.200.$ip OK" || echo "192.168.200.$ip FAILED"
ip=$(expr "$ip" "+" "1")
done
[root@master ~]#
执行
[root@master ~]# sh ip_usable.sh
192.168.200.1 FAILED
192.168.200.2 OK
192.168.200.3 FAILED
192.168.200.4 FAILED
192.168.200.5 FAILED
192.168.200.6 FAILED
192.168.200.7 FAILED
192.168.200.8 FAILED
192.168.200.9 FAILED
192.168.200.10 FAILED
192.168.200.11 FAILED
192.168.200.12 FAILED
192.168.200.13 FAILED
192.168.200.14 FAILED
192.168.200.15 FAILED
192.168.200.16 FAILED
192.168.200.17 FAILED
192.168.200.18 FAILED
Terminated
[root@master ~]#
也可以只打印可用的ip,做如下修改
#!/bin/bash
#sehn
ip=1
while [ $ip -ne "254" ]; do
ping 192.168.200.$ip -c 2 | grep -q "ttl=" && echo "192.168.200.$ip OK" || echo "192.168.200.$ip FAILED" >/dev/nul
l 2>&1
ip=$(expr "$ip" "+" "1")
done
当然也可以批量检测多个网段的可用ip
[root@master ~]# cat ip_usable.sh
#!/bin/bash
#sehn
ip=1
while [ $ip -ne "254" ]; do
ping 192.168.200.$ip -c 2 | grep -q "ttl=" && echo "192.168.200.$ip OK" || echo "192.168.200.$ip FAILED" >/dev/null 2>&1
ping 192.168.201.$ip -c 2 | grep -q "ttl=" && echo "192.168.201.$ip OK" || echo "192.168.201.$ip FAILED" >/dev/null 2>&1
ping 192.168.202.$ip -c 2 | grep -q "ttl=" && echo "192.168.202.$ip OK" || echo "192.168.202.$ip FAILED" >/dev/null 2>&1
ping 192.168.203.$ip -c 2 | grep -q "ttl=" && echo "192.168.203.$ip OK" || echo "192.168.203.$ip FAILED" >/dev/null 2>&1
ip=$(expr "$ip" "+" "1")
done
[root@master ~]#