Skip to content

Instantly share code, notes, and snippets.

@rjhornsby
Last active April 16, 2023 05:46
Show Gist options
  • Save rjhornsby/544cd3d79ca8f813762a246735789362 to your computer and use it in GitHub Desktop.
Save rjhornsby/544cd3d79ca8f813762a246735789362 to your computer and use it in GitHub Desktop.
Show EdgeOS DHCP lease table
#!/bin/bash
# Quickly show the Ubiquity EdgeOS (ie EdgeRouter Lite)
# DHCP leases to identify devices (ie headless raspberrypi)
# without having to go through the EdgeOS web UI.
#
# Thanks to @matthew1471 for API docs
# https://github.com/matthew1471/EdgeOS-API
# requires jq - `brew install jq` on macOS
function detect_gateway_addr {
case $(uname) in
Darwin)
while read -r hw; do
# the first interface that has a router addr
gateway=$(networksetup -getinfo "$hw" | awk '/^Router/ { print $2 }')
[ -n "$gateway" ] && break
done< <(networksetup -listallnetworkservices)
;;
Linux)
gateway=$(ip route | awk '/^default/ { print $3 }')
;;
*)
>&2 echo "Not sure what to do with OS $(uname)"
;;
esac
if [ -z "$gateway" ]; then
>&2 echo "Unable to figure out your gateway/router address"
>&2 echo "Trying setting EDGE_DEVICE_ADDR to your gateway's IP address"
exit 1
fi
echo $gateway
}
# For the sake of argument here, we're assuming the gateway/router
# is also the DHCP server. Bypass this by setting EDGE_DEVICE_ADDR.
[ -z "$EDGE_DEVICE_ADDR" ] && EDGE_DEVICE_ADDR=$(detect_gateway_addr)
if [ -z "$ERL_USERNAME" ] || [ -z "$ERL_PASSWORD" ]; then
>&2 echo "set ERL_USERNAME and ERL_PASSWORD env vars"
exit 1
fi
base_url="https://${EDGE_DEVICE_ADDR}:443"
curl -sk -c $HOME/.erl_cookie ${base_url}/ -d "username=${ERL_USERNAME}&password=${ERL_PASSWORD}"
json=$(curl -sk -b $HOME/.erl_cookie ${base_url}/api/edge/data.json\?data\=dhcp_leases)
IFS='' read -r -d '' jq_filter <<-'FILTER'
.output."dhcp-server-leases".LAN1
| keys[] as $k
| [
$k,
.[$k].mac,
.[$k]."expiration",
.[$k]."client-hostname"
]
| @tsv
FILTER
echo $json | jq -r "$jq_filter"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment