Successfully Monitoring Unifi AP with Python Script

Hey everyone, I wanted to share my recent success in monitoring my Unifi AP using a Python script. I’ve been looking for a way to get more detailed information about my network, such as CPU usage, RAM, and the number of connected clients. After some research, I came across the unificontrol Python module, which seemed perfect for the job.

I decided to write a script that pulls data from my Unifi controller. The process involved setting up the module, connecting to my controller, and pulling various stats like system information and device details. Here’s a snippet of the script I wrote:

python
from unificontrol import UnifiClient
from datetime import timedelta
import json

Fill in your Unifi controller credentials

host = ‘your_controller_ip’
username = ‘your_username’
password = ‘your_password’
site = ‘default’
port = 443
mac = ‘your_ap_mac_address’

client = UnifiClient(host=host, username=username, password=password, site=site, port=port)
stat = client.stat_sysinfo()
devs = client.list_devices(mac)
clients = client.list_clients()
guests = client.list_guests()

Extract relevant data

numclients = len(clients)
numguests = len(guests)
cpu = float(devs[0][‘system-stats’][‘cpu’])
ram = float(devs[0][‘system-stats’][‘mem’])
uptime = devs[0][‘uptime’]

Print the results

print(f"Connected Clients: {numclients}“)
print(f"Guests: {numguests}”)
print(f"CPU Usage: {cpu}%“)
print(f"RAM Usage: {ram}%”)
print(f"Uptime: {uptime} seconds")

After setting up the script, I integrated it into Home Assistant by creating a command_line sensor in my configuration.yaml file. This allows me to monitor all the collected data directly from my dashboard. Here’s how I configured it:

yaml

  • platform: command_line
    command: ‘python3 /path/to/your/script.py’
    name: unifi_ap_stats
    value_template: ‘{{ value_json }}’
    scan_interval: 60

I also created some template sensors to display specific metrics like CPU and RAM usage. This setup has been incredibly helpful in keeping my network running smoothly. I can now easily track performance and troubleshoot any issues that arise.

If anyone has questions or wants to share their own monitoring scripts, I’d love to hear from you! Happy scripting! :rocket: