1.检测整个局域网内存活的主机(仅适用ping,不使用nmap)
ping 广播地址需要加-b,进行另外判断
#!/bin/bash #define functions usage() { echo "usage:$0 192.168.1" } #check ip if [ -z $1 ]; then usage exit 0 fi #check the whole net for((i=1;i<256;i++)); do #ping broadcarst need to add -b if [ $i -eq 255 ]; then ping -b -c 1 $1.$i | grep -o ttl >> /dev/null else ping -c 1 $1.$i | grep -o ttl >> /dev/null fi #check if the ping is succeed if [ $? -eq 0 ]; then echo "$1.$i is up" fi done
2.根据ip地址查找mac地址
首先ping一次ip,用于刷新arp cache,以防存活的主机不再arp cache中
#!/bin/bash ###first ping the host to refresh the arp cache,then check the arp list### #define function usage() { echo "usage:$0 192.168.1.2" } #check the ip if [ -z $1 ]; then usage exit 0 fi #fresh the arp cache ping -c 1 $1 > /dev/null if [ $? -eq 0 ]; then echo -n "Host is up.Mac is " arp -a | grep "($1)" | awk '{print $4}' else echo "host is down" fi
基于nmap软件,所以首先需要apt-get install nmap
#!/bin/bash #define function usage() { echo "usage: $0 00:00:00:00:00:11" } #check user if [ $UID -ne 0 ]; then echo "plesase run this with sudo" exit 0 fi #check parameter if [ -z $1 ]; then usage exit 0 fi #not capitalized is converted to uppercase mac=`echo $1 | tr '[a-z]' '[A-Z]'` #check host nmap -sP 192.168.1.0/24 > temp.txt && grep -n $mac temp.txt > /dev/null if [ $? -eq 0 ]; then line=`awk '/'$mac'/{print NR}' temp.txt` awk NR==$line-2 temp.txt && awk NR==$line-1 temp.txt && awk NR==$line temp.txt exit 0 else echo "host doesn't exist" fi rm temp.txt