Created
February 28, 2015 01:45
-
-
Save ubergesundheit/e62943343a161eb1ca84 to your computer and use it in GitHub Desktop.
Check if mac-adress is online, call with ./check-mac.sh 11:11:11:11:11:11
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
( | |
set -f # turn of globbing, the file contains probably an * | |
MAC_TO_CHECK=$1 | |
ARP_FILE=/proc/net/arp | |
STATUS=unreachable | |
# try to find the host based on existing arp cache entries | |
# return values are: | |
# 0 = mac is online | |
# 1 = mac is in arp but seems offline | |
# 2 = mac is not in arp | |
# 3 = should not happen | |
check_arp_file () | |
{ | |
local was_in_arp=false | |
local is_online=false | |
while read line | |
do | |
was_in_arp=true | |
ping -n -q -c 1 `echo $line | cut -d" " -f 1` > /dev/null 2>&1 | |
if [ $? -eq 0 ]; then | |
is_online=true | |
break | |
fi | |
done < <(cat $1 | grep -i $2) | |
if [ "$was_in_arp" = true ] && [ "$is_online" = true ]; then | |
return 0 | |
elif [ "$was_in_arp" = true ] && [ "$is_online" = false ]; then | |
return 1 | |
elif [ "$was_in_arp" = false ]; then | |
return 2 | |
fi | |
return 3 | |
} | |
if [ ! -e "$ARP_FILE" ] # check if the arp file exists | |
then | |
exit 1 | |
fi | |
if [ ! -r "$ARP_FILE" ] # check if the arp file is user readable | |
then | |
exit 1 | |
fi | |
if ! check_arp_file $ARP_FILE $MAC_TO_CHECK; then | |
# was not online, ping all hosts in subnet | |
ip_base=`hostname --all-ip-addresses | cut -d. -f1,2,3` | |
for i in `seq 1 255`; do | |
ping -n -q -W 2 -c 1 $ip_base.$i > /dev/null 2>&1 & | |
pids="$pids $!" | |
done | |
wait $pids | |
check_arp_file $ARP_FILE $MAC_TO_CHECK | |
if [ $? -eq 0 ]; then | |
STATUS=reachable | |
fi | |
else | |
STATUS=reachable | |
fi | |
echo -n "{\"mac\":\"$MAC_TO_CHECK\",\"status\":\"$STATUS\",\"timestamp:\"`date +%s`\"}" | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment