Skip to content

Instantly share code, notes, and snippets.

@cmlewis89
Last active September 25, 2023 20:11
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save cmlewis89/35e71284cc3c7deef8759e8f07f4e8db to your computer and use it in GitHub Desktop.
Save cmlewis89/35e71284cc3c7deef8759e8f07f4e8db to your computer and use it in GitHub Desktop.
Bash script to monitor any new device connects to a network using arp
#!/bin/bash
#
# arp-monitor, an ARP tables monitor
# inspired by https://gist.github.com/maugern/30ace2764aafc683a802de2ed82f91af
#
# This script is intended to start on launch and run on an always connected device on a network (eg: server).
# It scans the network with 'arp -a' and sends a notification webhook whenever recognizes a new mac address on the network.
#
# For auto-run on login you can rename the script to a .command and add it to your Login items on Mac OS or
# modify the script to remove the loop and take a look at crontab
#
# Note: Ensure you change the Discord variable below to your own webhook
#
#discord webhook
DISCORD_WEBHOOK="https://discordapp.com/api/webhooks/***"
#save
ARP_MAC_SAVE="ARP_MAC.txt"
#temp files
ARP_TABLE="ARP_temp.txt"
ARP_MACS="ARP_MAC_temp.txt"
ARP_MAC_COMBO="ARP_MAC_combo.txt"
ARP_MAC_DIFF="ARP_MAC_diff.txt"
while true
do
# Fetch a new arp output
arp -an > $ARP_TABLE
# Filter only mac addreses
cat $ARP_TABLE | awk '{print $4}' | sort > $ARP_MACS
# Check if history does not already exist
if [ ! -f $ARP_MAC_SAVE ]; then
echo "No file $ARP_MAC_SAVE found. Copying actual ARP table."
cp -f $ARP_MACS $ARP_MAC_SAVE
fi
# Add save to new fetch and removing dupes
cat $ARP_MAC_SAVE $ARP_MACS | sort | uniq > $ARP_MAC_COMBO
# Diff the current arp with saved history
diff $ARP_MAC_COMBO $ARP_MAC_SAVE --ignore-all-space | grep "<" | awk '{print $2}' > $ARP_MAC_DIFF
# Act on any diff
if [ -s $ARP_MAC_DIFF ]; then
# loop through new mac addresses
while read -r i; do
# pull full data from ARP table
newARP=$(cat $ARP_TABLE | grep "$i")
# attempt to pull vendor info from mac address prefix with '${i:0:8}'
vendorAPI="https://macvendors.co/api/${i:0:8}/pipe"
vendorID=$(curl "$vendorAPI" | awk -F'\\|' '{print $1}' | sed 's/\"//g')
# log
echo "Found a new client mac address: $newARP from vendor $vendorID"
# send discord notification
curl -H "Content-Type: application/json" -X POST -d '{"content": "**New client on network**: '"$newARP"' from vendor '"$vendorID"' "}' "$DISCORD_WEBHOOK"
#delay before next result
sleep 2
done < $ARP_MAC_DIFF
# Update old arp save
cp -f $ARP_MAC_COMBO $ARP_MAC_SAVE
fi
# Remove all temp files
rm -f $ARP_TABLE $ARP_MACS $ARP_MAC_COMBO $ARP_MAC_DIFF
# Delay before next run
sleep 1
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment