Skip to content

Instantly share code, notes, and snippets.

@trygvis
Last active September 13, 2015 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trygvis/52a93b68dc032d763f4f to your computer and use it in GitHub Desktop.
Save trygvis/52a93b68dc032d763f4f to your computer and use it in GitHub Desktop.
usage: arp-to-mqtt [-t <prefix>] [-h host] [-i <interface>]

A utility script to dump an ARP table to a set of MQTT topics.

For each MAC with an IP publish a message to

<prefix>/<mac of interface>/<mac of device>/ip

and

<prefix>/<mac of interface>/<mac of device>/hostname

if the IP was resolved to a hostname

#!/bin/bash
set -e
PATH=/bin:/sbin:/usr/bin:/usr/sbin:
mqtt_broker=localhost
mqtt_id=arp_to_mqtt_$(hostname --fqdn)
if=eth0
topic_prefix=/arp
arp_args=()
while getopts ":h:t:i:n" opt; do
case $opt in
h)
mqtt_broker="$OPTARG"
OPTIND=1
shift 2
;;
t)
topic_prefix="$OPTARG"
OPTIND=1
shift 2
;;
i)
if="$OPTARG"
OPTIND=1
shift 2
;;
n)
arp_args+=(-n)
OPTIND=1
shift
;;
*)
echo "Invalid option: -$OPTARG" >&2
exit 1
break
;;
esac
done
if [ $# -gt 0 ]
then
echo "Bad argument: $@"
exit 1
fi
if_mac=$(/sbin/ifconfig "$if"|sed -n -e 's,.*ether \([^ ]*\) .*,\1,p')
pub() {
path=$1; shift;
msg=$1; shift;
# echo -e "$path" "\t=\t" "$msg"
opts=()
if [[ $msg == "" ]]
then
opts+=(-n)
# return
else
opts+=(-m)
opts+=("$msg")
fi
opts+=(-q 0)
opts+=(-r)
mosquitto_pub -i "$mqtt_id" -h "$mqtt_broker" -t "$topic_prefix/$path" "${opts[@]}"
}
timestamp=$(date +%s)
/usr/sbin/arp -i "$if" "${arp_args[@]}" -a | \
sed -n -e '/<incomplete>/d' \
-e 's,\([^ ]\) (\([^)]*\)) at \([^ ]*\) .*,\1;\2;\3,p' | while IFS=';' read hostname ip mac rest
do
# pub "$if_mac/$mac" ""
pub "$if_mac/$mac/ip" "$ip"
if [[ $hostname == '?' ]]
then
hostname=""
fi
pub "$if_mac/$mac/hostname" "$hostname"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment