Use when asked about UniFi network gear or the local network — access points, gateway, switches, WiFi, or which clients/devices are connected. Queries the lo...
安全
unifly
试用用同一个 CLI 管理 UniFi:集成 API、Session API、Site Manager 云端 API 与 WebSocket 事件流。
它能做什么
unifly 是用 Rust 编写的命令行工具,把 UniFi 的 Integration API、Session API、Site Manager 云端 API 与 WebSocket 实时事件流整合在 28 个顶层命令下,覆盖设备、客户端、网络、WiFi、防火墙策略与区域、NAT、ACL、DNS、流量匹配列表、热点 voucher、DPI、统计、备份、VPN、站点设置以及云端主机查询等场景。它通过双 API 合并拉取 Session 独有的客户端流量、主机名、上行 MAC 等数据,并叠加仅在 Integration 上开放的配置 CRUD。未被命令直接包装的接口可通过 `unifly api` 原样透传到控制器。
什么时候用它
- 以代码化方式在 UniFi 控制器上下发 VLAN、SSID 与防火墙策略
- 排障时通过 WebSocket 实时观察事件流
- 对防火墙策略做确定性、可往返的顺序调整
- 用 `-p home` / `-p office` 等 profile 同时管理多台控制器
技能文档
unifly: UniFi Network Management
unifly is a Rust CLI for managing Ubiquiti UniFi network infrastructure. It unifies the modern Integration API (REST, API key), the Session API (cookie plus CSRF), and Site Manager cloud APIs behind a single coherent interface, plus real-time WebSocket event streaming. 28 top-level commands cover devices and switch port config-as-code, clients, networks, WiFi, firewall policies, zones, and groups, NAT policies, ACLs, DNS, traffic matching lists, hotspot vouchers, DPI, stats, backups, the full VPN surface, site settings, cloud fleet queries, and a raw API escape hatch.
Unique capabilities worth leading with when the user's task suits them:
- Dual-API enrichment merges Integration and Session data (e.g. client bytes, hostnames, uplink MACs only exist in the Session API; configuration CRUD only exists in Integration). On UniFi OS, API key mode can already reach session HTTP; Hybrid adds the WebSocket session for live monitoring.
- Real-time event streaming via
unifly events watchover WebSocket. - Firewall policy reordering via
reorder --get/reorder --setfor deterministic, round-trippable ordering edits. unifly apiraw passthrough for endpoints unifly does not wrap.- Multi-profile (
-p home,-p office) for managing multiple controllers from one command line.
Prerequisites
Verify availability before running any command:
command -v unifly >/dev/null 2>&1 && unifly --version || echo "unifly not installed"
If unifly is not installed, prefer brew install hyperb1iss/tap/unifly on
macOS or cargo install --git https://github.com/hyperb1iss/unifly.git unifly
elsewhere. After install, run unifly config init for a local controller or
unifly config cloud-setup for Site Manager. See examples/config.toml for
manual configuration.
Authentication Modes
unifly supports four modes. API key mode is enough for most HTTP
automation on UniFi OS controllers. Choose Hybrid when the task needs
live WebSocket features (events watch) or you want maximum compatibility.
| Mode | Credentials | What It Unlocks |
|---|---|---|
integration | API key | Integration API plus session HTTP on UniFi OS: CRUD, device commands, stats, reservations, admin, event list |
session | Username + password | Session HTTP + WebSocket only: events watch, stats, device commands, DPI control, admin, backups, NAT policies, firewall groups, switch port config-as-code, site settings |
hybrid | API key + username/pass | Everything above, including session WebSocket plus enriched records with maximum controller compatibility |
cloud | Site Manager API key | Connector-routed Integration CRUD plus unifly cloud fleet commands against api.ui.com |
Session WebSocket still rejects API keys, so events watch needs session or
hybrid. Cloud mode does not expose Session API endpoints or WebSocket
streaming.
For the complete command-to-API gate matrix (which commands require which
auth mode), consult references/concepts.md.
Command Inventory
All commands follow unifly [global-flags] [args].
| Command | Aliases | Actions |
|---|---|---|
devices | dev, d | list, get, adopt, remove, restart, locate, port-cycle, ports, ports-export, port-set, stats, pending, upgrade, provision, speedtest, tags |
clients | cl | list, find, get, roams, wifi, authorize, unauthorize, block, unblock, kick, forget, reservations (res), set-ip, remove-ip |
cloud | hosts [get], sites, switch, devices, isp [query], sdwan [get, status] | |
networks | net, n | list, get, create, update, delete, refs |
wifi | w | list, get, neighbors, channels, create, update, delete |
firewall | fw | policies {list, get, create, update, patch, delete, reorder}, zones {list, get, create, update, delete}, groups {list, get, create, update, delete} |
nat | policies {list, get, create, update, delete} | |
acl | list, get, create, update, delete, reorder | |
dns | list, get, create, update, delete | |
traffic-lists | list, get, create, update, delete | |
hotspot | list, get, create, delete, purge | |
events | list, watch | |
alarms | list, archive, archive-all | |
stats | site, device, client, gateway, dpi | |
dpi | apps, categories, status, enable, disable | |
topology | topo | (no subcommands) |
system | sys | info, health, sysinfo, backup {create, list, download, delete}, reboot, poweroff |
settings | list, get, set, export | |
sites | list, create, delete | |
admin | list, invite, revoke, update | |
wans | list | |
vpn | servers [get], tunnels [get], status, health, site-to-site {list, get, create, update, delete}, remote-access {list, get, create, update, suggest-port, download-config, delete}, clients {list, get, create, update, delete}, connections {list, get, restart}, peers {list, get, create, update, delete, subnets}, magic-site-to-site {list, get}, settings {list, get, set, patch} | |
radius | profiles | |
countries | (no subcommands) | |
api | Raw API passthrough (GET/POST/PUT/PATCH/DELETE any path) | |
config | init, cloud-setup, show, set, profiles, use, set-password, theme | |
tui | (no subcommands) | |
completions | bash, zsh, fish, powershell, elvish |
For flag details and gotchas, consult references/commands.md. Every entity
command accepts --help at runtime as the authoritative reference.
Output Formats
All list and get commands accept --output / -o:
| Format | Flag | Use Case |
|---|---|---|
table | -o table | Human display (default) |
json | -o json | Agent processing, pipe to jq |
json-compact | -o json-compact | Single-line JSON for scripting |
yaml | -o yaml | Config file output |
plain | -o plain | One ID per line for xargs pipelines |
Default for agent use: -o json. Emit structured output, pipe through
jq, and only fall back to table when the result is being shown to a human.
Power Patterns
These patterns unlock unifly's most distinctive capabilities. For full
recipes with runnable shell scripts, consult references/workflows.md.
--from-file for complex create/update
Most entities accept --from-file (or -F) instead of flag
salad: networks, wifi, firewall policies, firewall zones, firewall groups, nat policies, acl, dns, traffic-lists, vpn site-to-site, vpn remote-access, vpn clients, vpn peers, vpn settings patch, and devices port-set (JSONC for switch port config-as-code).
Construct the JSON payload, validate it, then apply. See examples/ for
payload templates.
unifly networks create -F examples/network-iot-vlan.json
unifly firewall policies create -F examples/firewall-block-iot.json
Real-time event streaming
# All events
unifly events watch
# Filter by EventCategory (case-insensitive): Device, Client, Network,
# System, Admin, Firewall, Vpn, Unknown
unifly events watch --types "Firewall,Admin"
# JSON stream for piping into alerting (severity serializes PascalCase)
unifly events watch --types Client -o json | jq -c 'select(.severity == "Warning")'
Firewall policy reorder (round-trippable)
# Read current order for a zone pair
unifly firewall policies reorder --source-zone --dest-zone --get
# Write back an explicit order
unifly firewall policies reorder --source-zone --dest-zone \
--set ",,"
Raw API escape hatch
For endpoints unifly does not wrap (including UniFi v2 routes and Integration
paths), use unifly api. It routes through the Session client, so CSRF token
management and session caching are automatic.
unifly api "v2/api/site/default/traffic-flow-latest-statistics"
unifly api "cmd/stamgr" -m post -d '{"cmd":"kick-sta","mac":"aa:bb:cc:dd:ee:ff"}'
unifly api "api/s/default/set/setting/teleport" -m put -d '{"enabled":true}'
Session API VPN payloads and settings
unifly vpn site-to-site wraps Session API rest/networkconf records whose
purpose is site-vpn. This is the current CRUD path for manual IPsec and
OpenVPN site-to-site records exposed by the controller.
unifly vpn site-to-site list -o json
unifly vpn site-to-site get -o json
unifly vpn site-to-site create -F site-to-site.json
unifly vpn site-to-site update -F site-to-site.json
unifly vpn site-to-site delete
unifly vpn remote-access wraps Session API rest/networkconf records whose
purpose is remote-user-vpn. This is the current CRUD path for L2TP,
OpenVPN, and WireGuard remote-access servers exposed by the controller.
unifly vpn remote-access list -o json
unifly vpn remote-access get -o json
unifly vpn remote-access create -F remote-access.json
unifly vpn remote-access update -F remote-access.json
unifly vpn remote-access suggest-port -o json
unifly vpn remote-access download-config --path .
unifly vpn remote-access delete
unifly vpn clients wraps Session API rest/networkconf records whose
purpose is vpn-client. This is the current CRUD path for configured
OpenVPN and WireGuard client profiles exposed by the controller.
unifly vpn clients list -o json
unifly vpn clients get -o json
unifly vpn clients create -F vpn-client.json
unifly vpn clients update -F vpn-client.json
unifly vpn clients delete
unifly vpn peers wraps the Session v2 API WireGuard peer endpoints for
remote-access VPN servers. list can enumerate all peers or scope to a
single server ID; create, update, and delete require the parent
remote-access server ID.
unifly vpn peers list -o json
unifly vpn peers list -o json
unifly vpn peers get -o json
unifly vpn peers create -F peer.json
unifly vpn peers update -F peer.json
unifly vpn peers delete
unifly vpn peers subnets -o json
unifly vpn connections wraps the Session v2 API VPN client connection
inventory exposed at v2/api/site//vpn/connections. restart
issues the same controller action the web UI uses for a single connection.
unifly vpn connections list -o json
unifly vpn connections get -o json
unifly vpn connections restart
unifly vpn magic-site-to-site wraps the Session v2 API
magicsitetositevpn/configs inventory endpoint. It is currently
read-only.
unifly vpn magic-site-to-site list -o json
unifly vpn magic-site-to-site get -o json
unifly vpn settings wraps the Session API rest/setting records for the VPN
feature toggles the controller exposes today: teleport,
magic-site-to-site-vpn, openvpn, and peer-to-peer.
unifly vpn settings list -o json
unifly vpn settings get peer-to-peer -o json
unifly vpn settings set teleport --enabled true
unifly vpn settings patch peer-to-peer -F peer-to-peer.json
site-to-site get, remote-access get, clients get, connections get,
peers get, and magic-site-to-site get return redacted records with
summary fields and the sanitized controller payload under fields.
settings get returns a redacted wrapper with key, enabled, and fields.
patch accepts either the raw session setting body or that wrapper shape and
will send the inner fields object back to the controller.
Bulk operations via filter DSL
hotspot purge --filter accepts the Integration filter DSL for bulk deletion
without ID iteration:
unifly hotspot purge --filter "status.eq('UNUSED')"
unifly hotspot purge --filter "name.contains('Conference')"
TUI handoff for human verification
Propose a change, let a human visually confirm in the TUI before committing:
# Agent inspects, proposes. Human runs unifly tui and verifies on
# screen 4 (Networks) or 5 (Firewall) before the agent applies the change.
unifly tui
Multi-profile targeting
unifly -p home devices list
unifly -p office firewall policies list
UNIFI_PROFILE=warehouse unifly system health
Essential Gotchas
- Default list limit is 25 (a few commands default higher: hotspot,
events, and alarms use 100;
clients roamsuses 50). The CLI prints a truncation hint when results hit the default. For enumeration, always pass--allor--limit 200(or higher). - Environment variables use the
UNIFI_prefix, notUNIFLY_. Relevant vars:UNIFI_URL,UNIFI_API_KEY,UNIFI_USERNAME,UNIFI_PASSWORD,UNIFI_SITE,UNIFI_PROFILE,UNIFI_OUTPUT,UNIFI_INSECURE,UNIFI_TIMEOUT,UNIFI_TOTP,UNIFI_HOST_ID,UNIFI_DEMO. The onlyUNIFLY_*var isUNIFLY_THEME, which themes both CLI output and the TUI. --yes/-yskips confirmation prompts for mutations. Required for non-interactive use.- API key mode covers most commands on UniFi OS, including Session API
endpoints (stats, device commands, Wi-Fi observability, client enrichment).
Use Hybrid only when live WebSocket streaming is needed (
events watch, TUI live refresh). Client and device enrichment fields work in API key mode. - Cloud support is Integration-only.
unifly cloud ...talks to Site Manager andauth_mode = "cloud"routes Integration-backed commands through the connector, but Session-only features still need direct controller access. - Exit codes are meaningful.
0on success, non-zero on error. Capture stderr for diagnostics. - Create commands print the created entity on stdout in the chosen
--outputformat, with the confirmation on stderr. Capture IDs directly:ID=$(unifly networks create ... -o json | jq -r .id);-o plainemits the bare ID. Exceptions that print nothing because the controller returns no record:sites createandsystem backup create.
Agent Workflow
- Verify the tool exists with
command -v unifly. - Check auth mode with
unifly config showbefore running commands that require Session or Integration specifically. - Run
unifly system health -o jsonas the first touch to confirm connectivity. - Inspect before mutating:
list/getthe entity first, capture IDs. - For complex creates, write a JSON payload and use
--from-file. - After mutations, re-fetch the entity with
getto confirm state. - For irreversible operations (delete, reboot, poweroff), surface a
summary to the user before running even with
--yes.
Additional Resources
Reference Files
references/commands.md: Per-command flag reference with gotchas (non-obvious flags, dual-API boundaries, correct argument forms)references/concepts.md: UniFi networking concepts, dual-API gate matrix, auth decision tree, environment variables, platform config paths, MFA/TOTP, error taxonomyreferences/workflows.md: Runnable automation recipes (event streaming, safe firewall reorder, bulk DHCP reservations, ad-blocking via DNS policies, cafe voucher flow, incident response)
Example Files
examples/config.toml: Multi-profile config templateexamples/network-iot-vlan.json: VLAN creation payload for--from-fileexamples/firewall-block-iot.json: Firewall policy payloadexamples/nat-masquerade.json: NAT masquerade policy payloadexamples/nat-port-forward.json: Destination NAT (port forward) payloadexamples/wifi-iot.json: WiFi SSID payloadexamples/vpn-remote-access-wireguard.json: WireGuard remote-access VPN payloadexamples/vpn-site-to-site-ipsec.json: IPsec site-to-site tunnel payloadexamples/vpn-client-openvpn.json: OpenVPN client payloadexamples/vpn-wireguard-peer.json: WireGuard peer configuration payloadexamples/switch-ports.jsonc: Switch port config-as-code payload fordevices port-set -F
常见问题
- 该选哪种认证模式?
- 在 UniFi OS 上做 HTTP 自动化用 API key(`integration`)就够了;若需要 `events watch` 这类 WebSocket 实时功能,切到 `hybrid`;跨控制器做云端批量查询则使用 `cloud` 模式 + Site Manager API key。
- 是否同时覆盖 Integration 和 Session API?
- 覆盖。`hybrid` 模式下两者都可用,例如客户端流量与上行 MAC 仅在 Session 可获取,配置 CRUD 仅在 Integration 提供,未被包装的接口可直接通过 `unifly api` 调用。
相关技能
Diagnose a private household UniFi network for Operator and discover non-secret local helper configuration. Use for Wi-Fi, internet, DNS, latency, packet los...
Use this skill whenever the user needs to operate a network fabric through a controller API — Cisco Meraki Dashboard (full read+write), Cisco Catalyst Center / DNA Center (read subset), Arista CloudVision Portal / CVP (read subset), or UniFi Network (self-hosted controller / UniFi OS console; read subset + device restart) — a one-shot fabric health overview; organization/site/container reads (list/get, licensing, admins, org-wide device statuses, API usage); network reads (list/get, VLANs, health alerts, traffic); device reads (inventory by model MX/MS/MR/MV/MG, status, uplinks, switch ports / interface stats, wireless SSIDs); client reads (list, detail, usage, connectivity); three flagship analyses — uplink loss & latency RCA (rank worst MX WAN uplinks + cause/action), network health score (composite per-network), and config template drift (settings drifted from a bound template); and eight guarded writes (reboot, blink LEDs, update device, update VLAN, claim/remove devices, bind/unbi
UnifAPI (unifapi.com). Use this skill for ANY UnifAPI request — reading, creating, and updating data. Whenever a task involves UnifAPI, use this skill instea...
Use this skill whenever the user needs to operate an OPNsense or pfSense firewall — a one-shot overview, firmware/health, interfaces and gateways, firewall rules with hit-counts and shadow analysis, NAT (port-forward/outbound/1:1), aliases and their entries, VPN (WireGuard/OpenVPN/IPsec), DHCP leases and static mappings, the firewall log and state table, three flagship RCAs (gateway health, rule hit/shadow, blocked traffic), and governed writes (toggle a rule, add/remove an alias entry, kill states, restart a service, apply/reconfigure to make edits live, reboot). Always use this skill for "OPNsense", "pfSense", "firewall rule", "port forward", "NAT", "alias", "WireGuard", "OpenVPN", "IPsec", "DHCP lease", "firewall log", "blocked traffic", "why is my WAN down", "gateway loss/latency", "unused / shadowed rules", "apply firewall changes", "reboot the firewall" when the context is an OPNsense/pfSense firewall. Do NOT use when the target is something other than an OPNsense/pfSense firewal
UniOne (unione.io). Use this skill for ANY UniOne request — reading, creating, and updating data. Whenever a task involves UniOne, use this skill instead of...