7/11/2022
MikroTik RouterOS API in Python — network automation step by step
TL;DR: RouterOS API + Python = automating MikroTik management without clicking in Winbox. The routeros-api library connects to a router and returns the interface list in 5 lines.
If you manage more than one MikroTik router, sooner or later you’ll start looking for a way to automate things. RouterOS has a built-in API on port 8728 (plain) or 8729 (SSL). Python with the routeros-api library is the simplest entry point.
Installation and connection
pip install routeros-api
import routeros_api
connection = routeros_api.RouterOsApiPool(
'192.168.88.1',
username='admin',
password='haslo',
plaintext_login=True
)
api = connection.get_api()
Fetching data
# List of interfaces
interfaces = api.get_resource('/interface')
for iface in interfaces.get():
print(f"{iface['name']} — {iface.get('comment', '-')}")
# IP addresses
addresses = api.get_resource('/ip/address')
for addr in addresses.get():
print(f"{addr['address']} on {addr['interface']}")
Adding NAT rules
nat = api.get_resource('/ip/firewall/nat')
nat.add(
chain='dstnat',
protocol='tcp',
dst_port='2222',
action='dst-nat',
to_addresses='192.168.10.200',
to_ports='22',
comment='SSH do serwera'
)
Exporting configuration
# Equivalent of /export in Winbox
response = api('/export')
config_text = '\n'.join(line.decode() for line in response if line)
with open('router-backup.rsc', 'w') as f:
f.write(config_text)
Practical use case: backing up 10 routers
import routeros_api
from datetime import date
routers = [
{'host': '10.0.1.1', 'name': 'router-glowny'},
{'host': '10.0.1.2', 'name': 'router-oddzial'},
# ...
]
for r in routers:
conn = routeros_api.RouterOsApiPool(r['host'], username='admin', password='haslo', plaintext_login=True)
api = conn.get_api()
response = api('/export')
config = '\n'.join(line.decode() for line in response if line)
filename = f"backup-{r['name']}-{date.today()}.rsc"
with open(filename, 'w') as f:
f.write(config)
conn.disconnect()
print(f"Backup {r['name']} — OK")
Run this via cron once a night and you have a history of configurations for all your routers in text files that you can commit to git.
Gotchas
Routers with firmware older than 6.45 may require plaintext_login=True. API v2 (RouterOS 7.x) has breaking changes — the library supports both versions but check the changelog.