Skip to content

Instantly share code, notes, and snippets.

@mschmitt
Last active March 30, 2019 08:52
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 mschmitt/adf6f1f076fa54431636959c42a2e6df to your computer and use it in GitHub Desktop.
Save mschmitt/adf6f1f076fa54431636959c42a2e6df to your computer and use it in GitHub Desktop.
CGI script to extract the client's currently used wifi access point from the Unifi Controller's RESTful API
#!/bin/bash
# https://ubntwiki.com/products/software/unifi-controller/api
UNIFI_BASE="https://localhost:8443"
UNIFI_USER="readonly"
UNIFI_PASS="password"
echo "content-type: text/plain; charset=utf-8"
echo "Refresh: 10"
echo ""
COOKIEJAR=$(mktemp)
CURLTMP=$(mktemp)
function cleanup() {
rm "$COOKIEJAR"
rm "$CURLTMP"
}
trap cleanup EXIT
function test_success () {
RC=$(jshon -e "meta" -e "rc" -u -F "$CURLTMP")
if [[ "$RC" != "ok" ]]
then
echo "API Error:"
jshon -e "meta" -F "$CURLTMP"
exit 1
fi
}
# Log in to controller
LOGIN_JSON="{\"username\":\"$UNIFI_USER\",\"password\":\"$UNIFI_PASS\"}"
curl --silent --insecure --cookie-jar "$COOKIEJAR" \
--data "$LOGIN_JSON" "$UNIFI_BASE/api/login" > "$CURLTMP"
test_success
# Get list of access points
curl --silent --insecure --cookie "$COOKIEJAR" --cookie-jar "$COOKIEJAR" \
--data "$LOGIN_JSON" "$UNIFI_BASE/api/s/default/stat/device" > "$CURLTMP"
test_success
# Map AP ethernet address to AP name
declare -A ACCESS_POINT
OBJECT_COUNT=$(jshon -e "data" -l -F "$CURLTMP")
for ((OBJECT_INDEX=0;OBJECT_INDEX<OBJECT_COUNT;OBJECT_INDEX++))
do
THIS_NAME=$(jshon -e "data" -e $OBJECT_INDEX -e "name" -u -F "$CURLTMP")
THIS_MAC=$(jshon -e "data" -e $OBJECT_INDEX -e "mac" -u -F "$CURLTMP")
ACCESS_POINT["$THIS_MAC"]="$THIS_NAME"
done
# Get list of connected stations
curl --silent --insecure --cookie "$COOKIEJAR" --cookie-jar "$COOKIEJAR" \
"$UNIFI_BASE/api/s/default/stat/sta" > "$CURLTMP"
test_success
# Walk the list of connected stations until IP address matches
OBJECT_COUNT=$(jshon -e "data" -l -F "$CURLTMP")
for ((OBJECT_INDEX=0;OBJECT_INDEX<OBJECT_COUNT;OBJECT_INDEX++))
do
THIS_IPADDRESS=$(jshon -e "data" -e $OBJECT_INDEX -e "ip" -u -F "$CURLTMP")
if [[ "$REMOTE_ADDR" == "$THIS_IPADDRESS" ]]
then
# Print details to browser
THIS_HOSTNAME=$(jshon -e "data" -e $OBJECT_INDEX -e "hostname" -u -F "$CURLTMP")
THIS_ACCESSPOINT=$(jshon -e "data" -e $OBJECT_INDEX -e "ap_mac" -u -F "$CURLTMP")
printf "%s\n%s\n%s\n" "$THIS_HOSTNAME" "$THIS_IPADDRESS" "${ACCESS_POINT["$THIS_ACCESSPOINT"]}"
break
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment