Lin*_*nux 9 ip mac-address ping arp
我想ping一个已知的MAC地址,我试图使用nmap:
sudo nmap -sP 192.168.15.1/24 | grep 20:64:32:3F:B1:A9
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,它ping所有255个IP地址(从192.168.15.1到192.168.15.255),直到得到我的MAC地址,这需要很长时间约4秒.
有什么想法吗?
使其更快的唯一方法是测试mac地址是否已经进入你的arp表
#!/bin/bash
# extract ip from local arp table
ip=$(arp | grep 20:64:32:3F:B1:A9 | awk ' { print $1 } ')
# found an ip tied to the mac address?
if [ ! -z $ip ]; then
# if found, do you want to ping it?
ping $ip
else
echo "Not found into local arp table. Trying another way..."
# wanna try your nmap strategy?
# sudo nmap -sP 192.168.15.1/24 | grep 20:64:32:3F:B1:A9
fi;
Run Code Online (Sandbox Code Playgroud)
这是另一个更简单的答案。
ping $(arp-scan --localnet | grep 80:1f:02:fa:90:b7 | awk ' { printf $1 } ')
Run Code Online (Sandbox Code Playgroud)
请注意,mac 地址必须使用小写字母。
arp-scan 似乎比 arp 运行得快得多。
上述很好的答案合并为一个脚本:(用法:macping aa:bb:cc:dd:ee:ff)
#!/bin/bash
network=192.168.1.1/24
if [ "$#" -ne 1 ]; then echo Usage example: $0 aa:bb:cc:dd:ee:ff; exit 2; fi;
nmap -sP -T4 $network >& /dev/null
ip=$(arp -n | grep $1 | awk ' { print $1 }')
ping $ip -n -q -c 2 -i 0.2 -w 1 >& /dev/null
if [ $? -eq 0 ]; then
echo Device is online \($ip\)
else
echo Device is offline
exit 1
fi;
Run Code Online (Sandbox Code Playgroud)
扩展:通过mac地址维护网络设备列表,并显示每个设备的在线/离线状态。
用途包括:
如果在线,则每个设备名称显示为绿色;如果离线,则每个设备名称显示为红色。
设备状态更改时,将显示桌面通知。
经过Linux Mint测试,应该可以在其他发行版上使用。
#!/bin/bash
#Create associated array's
declare -A devicelist #device name: mac address
declare -A statuslist #device name: online status
devicelist[Server01]=aa:bb:cc:dd:ee:01
devicelist[Server02]=aa:bb:cc:dd:ee:02
devicelist[MyPhone] =aa:bb:cc:dd:ee:03
devicelist[SmartTV] =aa:bb:cc:dd:ee:04
#Colour Constants
BRed='\033[1;31m'
BGreen='\033[1;32m'
Reset='\033[m'
function mactoip(){
echo $(arp -n | grep -i $mac | awk ' { print $1 }')
}
while [ true ]; do
clear
arp_cache_rebuilt=no
for devicename in ${!devicelist[@]}; do
status=OFFLINE
mac=${devicelist[${devicename}]}
ip=$( mactoip $mac )
if [ -z $ip ] && [ $arp_cache_rebuilt = "no" ]; then
#we need to rebuild the arp cache...
nmap -sn -T4 192.168.1.0/24 >& /dev/null
ip=$( mactoip $mac )
arp_cache_rebuilt=yes
fi;
if [ ! -z $ip ]; then
ping $ip -n -q -c 2 -i 0.2 -w 1 >& /dev/null
if [ $? -eq 0 ]; then status=ONLINE; fi
fi;
#if device's previous status not yet recorded, then set it now.
if [ ! ${statuslist[${devicename}]+_} ]; then statuslist[${devicename}]=$status; fi
if [ $status = "ONLINE" ]; then colour=$BGreen; else colour=$BRed; fi;
echo -e ${colour}${devicename}${Reset} - $ip
if [ ${statuslist[${devicename}]} != $status ]; then
notify-send -i ac-adapter -u critical -t 1000 $status "$devicename"
fi;
statuslist[$devicename]=$status
done
echo -
sleep 5
done
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
51638 次 |
| 最近记录: |