Combining the above good answers in one script: (Usage: 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;
Expansion. To save the list of network devices, by MAC address and display the status online / offline. Usage includes:
- Monitoring the status of your server
- check your internet connection up.
- checking if a specific device connects to your Wi-Fi
- checking your smart tv is really off.
- etc.
Each device name is displayed in green if it is turned on, red - in offline mode.
A desktop notification is displayed when the device status changes.
Tested under linux mint, should work on other distributions.
#!/bin/bash #Create associated array 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 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
source share