#!/bin/bash
IP=172.16.104
count=1
while [ "$count" -lt "255" ]; do
echo -en "Pinging ${IP}.${count}..."
ping -c1 -w1 -t5 ${IP}.${count} >/dev/null 2>&1
if [ "$?" -eq "0" ]; then
echo "OK"&&echo ${IP}.${count}>>ok.txt
else
echo "Failed"&&echo ${IP}.${count}>>failed.txt
fi
let count=$count+1
done
注:某些主机设置了禁ping,也会被判定为Failed,所以执行结果并不是十分准确
上面用ping方法所得结果不太准确,下面一种方法可解决
1、首先ping ip
2、arp -a 查看该ip是否有MAC信息,如果有,则已被使用
#!/bin/bash
IP=172.16.104
count=1
while [ "$count" -lt "255" ]; do
echo -en "${IP}.${count}..."
ping -c1 -w1 -t5 ${IP}.${count} >/dev/null 2>&1
mac=`arp -a|grep -E "\(${IP}.${count}\)"|awk -F"<|>" '{print $2}'`
if [[ "$mac" == "incomplete" ]]
then
echo "ip未被使用"&&echo ${IP}.${count}>>unuse.txt
else
echo "ip已被使用"&&echo ${IP}.${count}>>use.txt
fi
let count=$count+1
done
转载于:https://blog.51cto.com/quliren/2055737