← all cheat sheets
OPERATOR REFERENCE · MIKROTIK AUTOMATION

MikroTik RouterOS Automation Field Reference
API · Scripting · Fleet Tooling

access method → client/library → scripting pattern → guardrails → project blueprint → shared building blocks
Accuracy note: the RouterOS REST API ships from v7.1+ only; the binary API (ports 8728/8729) and RouterOS scripting exist on both v6 and v7 but with menu/property differences between them. Library names, default ports, and service defaults below reflect current RouterOS v7.x behavior — VERIFY-flagged items are worth confirming against the MikroTik wiki or /system resource print for your exact version before scripting against them at scale.
ACCESS · API / REST / SSH
automate
SCRIPT · Python / Ansible / .rsc
scale out
FLEET · many routers, one control plane
01 Automation Access Methods
MethodTransportAuthFormatBest For
RouterOS API (binary) TCP 8728 (plaintext) / 8729 (TLS) username/password, encrypted challenge since 6.43 binary "sentence" protocol Low-overhead scripted access from Python/Go/Node clients; widest library support
REST API TCP 80/443, path /rest/ HTTP Basic Auth JSON over HTTPS RouterOS v7.1+ only; easiest to script from curl, requests, or any HTTP-capable tool
SSH + script TCP 22 password or public key RouterOS CLI text / .rsc Push exported scripts, run one-off commands, works even on very old RouterOS
SNMP UDP 161 (v1/v2c/v3) community string / v3 auth+priv SNMP OIDs (MikroTik MIB) Read-only polling into existing monitoring stacks (Zabbix, LibreNMS, PRTG, Grafana)
Outbound fetch/webhook router-initiated HTTP(S) n/a (router is the client) HTTP(S) payload Router pushes events out via /tool fetch — alerting, event-driven automation
Harden the service first: /ip service disable telnet,ftp,api then /ip service set api-ssl disabled=no certificate=your-cert — automate over API-SSL or REST-over-HTTPS, never plaintext API/telnet on anything WAN-reachable.
02 Client Libraries & Tooling
PY

Python (binary API)

pip install routeros-api pip install librouteros
Both wrap the binary API sentence protocol; routeros-api has a more resource-oriented interface, librouteros is lower-level and lighter.
PY

Python (REST API)

import requests requests.get('https://10.0.0.1/rest/ip/address', auth=('automation','pass'), verify=True)
No special library needed — it's plain HTTPS + JSON, so any HTTP client in any language works.
AN

Ansible

ansible-galaxy collection install community.routeros
Ships api_modify/api_facts (idempotent, structured) and a raw command module — prefer api_modify for state you want to converge repeatably.
TF

Terraform

Community terraform-provider-routeros (unofficial) manages interfaces, firewall rules, DHCP, and more as declarative resources — useful for branch fleets managed the same way as cloud infra.
VERIFY — unofficial provider; pin an exact version and test against a lab device before trusting it on production routers.
GO

Go

go get github.com/go-routeros/routeros
Good fit for building a standalone monitoring agent or CLI tool you want to distribute as a single binary.
JS

Node.js

npm install node-routeros
Binary API client for Node — pairs well with an Express/Next.js backend for a self-service portal (see project blueprints below).
RS

RouterOS-native scripting

No external runtime at all — /system script + /system scheduler run entirely on-device. Best for edge-local logic (netwatch-triggered failover) that must keep working even if the central controller is unreachable.
03 Core API & Scripting Patterns

Connect (binary API)

import routeros_api pool = routeros_api.RouterOsApiPool( '10.0.0.1', username='automation', password='...', use_ssl=True, ssl_verify=True, plaintext_login=True) api = pool.get_api() api.get_resource('/ip/address').get()
plaintext_login=True is required for RouterOS 6.43+ / v7 — the old MD5-challenge login is deprecated.

Connect (REST API)

curl -s -u automation:pass \ https://10.0.0.1/rest/interface \ -H "Content-Type: application/json" curl -X PATCH -u automation:pass \ https://10.0.0.1/rest/interface/ether2 \ -d '{"disabled":"true"}'
🔎

Query / Filter Syntax

/interface print where running=yes GET /rest/interface?running=true
CLI print where, binary API ?property=value query words, and REST query-string filters all express the same "?" comparison word underneath.
{ }

RouterOS Script Basics

:local wanIP [/ip address get [find interface=ether10] address] :foreach i in=[/interface find] do={ :local n [/interface get $i name] :log info "iface: $n" }
:local/:global scope variables, :foreach/:if drive control flow — this is the language behind Scheduler jobs and Netwatch up/down scripts.

Scheduled Automation

/system scheduler add name=nightly-backup \ on-event="/system backup save name=auto" \ start-time=02:00:00 interval=1d
Runs entirely on-device — no external cron needed for simple, self-contained jobs.

Timeouts & Error Handling

The binary API has no built-in request timeout — a hung TCP session can block your client indefinitely. Wrap every call with your own timeout + retry/backoff, and treat "connection refused" and "auth failed" as distinct failure modes (the latter should alert, not retry silently).
04 Security & Guardrails for Automation
👤

Dedicated Automation User

/user group add name=automation-ro policy=api,rest-api,read,!write,!policy,!password,!sensitive /user add name=automation group=automation-ro password=...
Never automate through the default admin account — scope a group's policy down to only what the job actually needs (read-only for dashboards, a narrow write set for deployment tools).
🔒

Encrypt & Restrict the Service

/ip service set api-ssl disabled=no certificate=automation-cert address=10.0.0.0/24 /ip service disable api,telnet,ftp
⚠ never leave the plaintext API (8728) or telnet reachable from anything beyond a trusted management VLAN
🗝

Secrets Handling

Never hardcode router credentials in a script or commit them to git. Pull from environment variables, Ansible Vault, or a secrets manager (HashiCorp Vault, AWS Secrets Manager) — and rotate the automation account's password on a schedule.

Rate Limits & Concurrency

Small-CPU boards (e.g. L009UiGS-RM, 512MB RAM) can choke on many concurrent API sessions during a fleet-wide push. Throttle concurrency in the orchestrator and stagger batches rather than firing all devices at once.

Dry-Run / Diff Before Push

/export file=before-change
Pull a config export before and after any automated change, diff the two, and keep both in version control — this is your rollback path and your audit trail in one.
📄

Audit Every Automated Change

/system logging action add name=remote-syslog target=remote remote=10.0.0.5
Ship logs off-box, and have every automation-initiated change carry a comment= tag identifying the job/run that made it — makes "who changed this" answerable months later.
05 Project Blueprints
01/10
💾

Enterprise MikroTik Backup Manager

Scheduled binary + text backups pulled from a whole fleet, versioned and stored off-box.
  • /system backup save + /export file= per device
  • Pull via SFTP/API, commit .rsc to git for a diffable history
  • .backup binaries to object storage (S3/MinIO) with a retention policy
Binary backups are version/model-locked — .rsc export is the format that actually restores cross-model, so keep both.
02/10
🚀

Multi-Branch Configuration Deployment Tool

Push a templated baseline (VLANs, firewall, VPN) consistently across many branch routers.
  • Jinja2/Ansible template + per-branch variables (WAN IP, VLAN IDs)
  • Render .rsc, push via SSH import or batched REST calls
  • Run a dry-run/export-diff before applying to a live branch
⚠ RouterOS import stops on the first error and runs top-to-bottom — templates must be idempotent/safe to re-run, not just correct once
03/10
📡

ISP Failover Monitoring Dashboard

Poll WAN links across sites, visualize uptime, alert on failover events.
  • Local /tool netwatch for fast on-device failover (no dependency on a central poller)
  • Central collector polls REST API for /ip route and interface state every N seconds
  • InfluxDB/Prometheus + Grafana; alert via /tool fetch webhook on state change
04/10
🎫

Hotspot User Management System

Self-service portal to create/expire hotspot or PPPoE users and view usage.
  • /ip hotspot user, /ip hotspot active, rate-limit profiles
  • User Manager package for RADIUS-backed accounting on larger deployments
  • Web frontend calls REST/RADIUS to add/disable users and pull session accounting
05/10

Automated Firmware Upgrade Platform

Staged, fleet-wide RouterOS/RouterBOOT upgrades with pre-checks and rollback.
  • Canary subset first — pre-upgrade backup + health check via API
  • Trigger /system package update install, wait for reboot, re-verify
  • Halt fleet-wide rollout automatically on canary failure
⚠ reboot drops the API/SSH session mid-upgrade — the orchestrator must poll for the device coming back, not expect a synchronous response
06/10
🗂

Network Asset Inventory Portal

Continuously discovered, searchable inventory of every MikroTik device on the network.
  • /system routerboard print, /system license print per device
  • /ip neighbor print (MNDP/LLDP/CDP) for auto-discovery of new devices
  • Upsert into Postgres keyed by serial number; flag EOL RouterOS versions
07/10
🖥

Self-Service Network Operations Portal

Let NOC/L1 staff run pre-approved, scoped actions without full CLI/WinBox access.
  • Backend holds real router credentials — never handed to the end user
  • Fixed set of parameterized API calls mapped to role-gated UI buttons
  • Every action logged with the requesting user's identity
✓ never expose raw API/CLI access to end users — wrap it behind a whitelisted action set
08/10

Network Compliance Checker

Nightly job diffs live config against a security baseline and reports drift.
  • Pull /export per device, diff against a golden baseline template
  • Rule checks: telnet disabled, NTP configured, final firewall drop rule present, strong admin policy
  • Dashboard flags non-compliant devices; auto-remediate only low-risk items
09/10
📶

Wi-Fi Controller for CAPsMAN Environments

Centralize AP provisioning/monitoring for a fleet of MikroTik cAP/wAP access points.
  • /caps-man configuration + provisioning push SSID/security/channel plans
  • One router (e.g. RB5009) runs as CAPsMAN manager for the whole AP fleet
  • Poll /caps-man registration-table print for a live client/signal dashboard
VERIFY — RouterOS7 introduced CAPsMAN v2 alongside the legacy package; confirm which your release defaults to before scripting against it.
10/10
🤖

AI Network Assistant (LLM + RouterOS API)

Chat-driven assistant that answers status questions and executes approved changes.
  • LLM tool-use layer maps intents to a fixed set of tested, parameterized API wrappers
  • Read tools (status/logs/routes) can be broad; write tools need an explicit allow-list + confirmation
  • Never let the model pass raw free-form text into /system script run
⚠ treat router log/output text fed back into the assistant's context as untrusted — prompt injection from device output into an over-privileged assistant is a real risk
06 Shared Automation Building Blocks
💾

Backup & Export

/system backup save name=auto-$[/system clock get date] /export compact file=running-export

Scheduler Jobs

/system scheduler add name=job1 interval=1h \ on-event="/system script run health-check"
👁

Netwatch (event-driven)

/tool netwatch add host=8.8.8.8 interval=10s \ up-script=":log info \"WAN up\"" \ down-script=":log warning \"WAN down\""
{ }

System Script

/system script add name=health-check source={ :log info [/system resource get cpu-load] } /system script run health-check
🔔

Outbound Webhook

/tool fetch url="https://hooks.example.com/alert" \ http-method=post http-data="{\"msg\":\"WAN down\"}"
Router-initiated — works even when your central controller can't reach the router directly (NAT'd branch sites).
📊

SNMP Polling

/snmp set enabled=yes contact=noc@example.com location=hq snmpwalk -v2c -c public 10.0.0.1 1.3.6.1.2.1.1
07 Common Errors & Fixes
SymptomLikely Cause / Fix
API login fails: "invalid user name or password"missing plaintext_login=True (or library equivalent) — needed for RouterOS 6.43+/v7 login handshake
REST API call returns 404device is on RouterOS <7.1 (no REST support), or www-ssl service is disabled
Bulk push script hangs on a small devicetoo many concurrent API sessions against a low-RAM board — throttle concurrency
Netwatch script never firestest host itself is unreliable, or it's the same path as the thing you're trying to detect failing
Ansible community.routeros task not idempotentused the raw command module instead of api_modify/api_info for structured state
Scheduled job silently stops runninga script error can suspend future runs on some versions — check /log and /system scheduler print
ActionRisk
Automating over plaintext API (8728) or telnetinsecure credentials and commands travel unencrypted
Fleet-wide push with no canary/stagingdestructive a bad template can break every branch at once
Automation account with full/admin policycaution scope the group policy to only what each job needs
LLM assistant with unrestricted write accessdestructive pair any write capability with an explicit allow-list, never free-form command passthrough
/system backup load via automationcaution overwrites running config on load — treat as a rollback action, not a routine one
Read-only polling (SNMP, /interface print)safe low risk, good default scope for dashboards/inventory tools