Communicate with MikroTik RouterOS devices using the Python routeros-api library over the API port (8728 plain, 8729 SSL).
Install the library if not present:
bash
pip3 install --break-system-packages routeros-api
It is highly recommended to use environment variables for credentials to avoid hardcoding.
Set these in your environment or .env file:
MIKROTIK_HOST: Router IP or hostnameMIKROTIK_USERNAME: Router usernameMIKROTIK_PASSWORD: Router passwordpython
import routeros_api
import os
# Get credentials from environment variables
host = os.getenv('MIKROTIK_HOST')
username = os.getenv('MIKROTIK_USERNAME')
password = os.getenv('MIKROTIK_PASSWORD')
# Fallback to manual input if env vars are missing
if not all([host, username, password]):
print("Environment variables MIKROTIK_HOST, MIKROTIK_USERNAME, or MIKROTIK_PASSWORD are not set.")
# host = input("Enter Host: ") ...
conn = routeros_api.RouterOsApiPool(
host=host,
username=username,
password=password,
plaintext_login=True, # Required for RouterOS 6.43+
port=8728 # Use 8729 for SSL
)
api = conn.get_api()
# ... do work ...
conn.disconnect()
MIKROTIK_HOST, MIKROTIK_USERNAME, and MIKROTIK_PASSWORD.conn.disconnect() when done.plaintext_login=True for RouterOS v6.43+ and v7.x.python
conn = routeros_api.RouterOsApiPool(
host=host,
username=username,
password=password,
plaintext_login=True,
use_ssl=True,
ssl_verify=False, # Set True with proper certs
ssl_verify_hostname=False,
port=8729
)
python
resource = api.get_resource('/ip/address')
items = resource.get() # Get all
items = resource.get(interface='ether1') # Filter by param
items = resource.get(disabled='false') # Filter by status
python
resource = api.get_resource('/ip/address')
resource.add(address='192.168.1.1/24', interface='ether1')
# With comment
resource.add(address='192.168.1.1/24', interface='ether1', comment='Management')
python
resource = api.get_resource('/ip/address')
resource.set(id='*1', address='192.168.2.1/24')
resource.set(id='*1', comment='Updated via API')
resource.set(id='*1', disabled='yes') # Disable entry
resource.set(id='*1', disabled='no') # Enable entry
python
resource.remove(id='*1')
python
resource = api.get_resource('/system')
resource.call('reboot')
# Call with parameters
resource = api.get_resource('/ip/firewall/filter')
resource.call('move', {'numbers': '*1', 'destination': '*5'})
python
resource = api.get_resource('/interface')
resource.set(id='*1', disabled='yes') # Disable
resource.set(id='*1', disabled='no') # Enable
TaskResource PathSystem info (CPU, RAM, uptime)/system/resourceRouter identity/system/identitySystem clock/system/clockNTP client/system/ntp/clientNTP server/system/ntp/serverScheduler/system/schedulerScripts/system/scriptLogging rules/system/loggingLog entries/logPackages/system/packagePackage update/system/package/updateRouter board info/system/routerboardLicense/system/licenseHealth (voltage, temp)/system/healthHistory/system/historyUsers/userUser groups/user/groupActive users/user/activeSSH keys/user/ssh-keysFiles/fileBackup/system/backupSNMP/snmpSNMP community/snmp/communityCertificates/certificateConsole/system/consoleLEDs/system/leds
TaskResource PathAll interfaces/interfaceEthernet/interface/ethernetBridge/interface/bridgeBridge ports/interface/bridge/portBridge VLANs/interface/bridge/vlanBridge hosts (MAC table)/interface/bridge/hostBridge MSTi/interface/bridge/mstiBridge settings/interface/bridge/settingsVLAN/interface/vlanBonding (LACP/bonding)/interface/bondingEoIP tunnel/interface/eoipGRE tunnel/interface/greIPIP tunnel/interface/ipipVXLAN/interface/vxlanVXLAN VTEP/interface/vxlan/vtepWireGuard/interface/wireguardWireGuard peers/interface/wireguard/peersL2TP client/interface/l2tp-clientL2TP server/interface/l2tp-server/serverSSTP client/interface/sstp-clientSSTP server/interface/sstp-server/serverOVPN client/interface/ovpn-clientOVPN server/interface/ovpn-server/serverPPPoE client/interface/pppoe-clientPPPoE server/interface/pppoe-server/serverPPTP client/interface/pptp-clientPPTP server/interface/pptp-server/serverLTE/interface/lteLTE APN/interface/lte/apnWireless (WiFi legacy)/interface/wirelessWiFi (new, ROS 7)/interface/wifiWiFi channels/interface/wifi/channelWiFi datapath/interface/wifi/datapathWiFi security/interface/wifi/securityWiFi configuration/interface/wifi/configurationWiFi provisioning/interface/wifi/provisioningWiFi registration table/interface/wifi/registration-tableWiFi access list/interface/wifi/access-listWiFi interworking/interface/wifi/interworkingInterface lists/interface/listInterface list members/interface/list/memberEthernet switch/interface/ethernet/switchEthernet switch port/interface/ethernet/switch/portTraffic monitor/interface/monitor-traffic
TaskResource PathIP addresses/ip/addressARP table/ip/arpRoutes/ip/routeRoute rules/ip/route/ruleDNS settings/ip/dnsDNS static entries/ip/dns/staticDNS cache/ip/dns/cacheDHCP client/ip/dhcp-clientDHCP server/ip/dhcp-serverDHCP server network/ip/dhcp-server/networkDHCP server leases/ip/dhcp-server/leaseDHCP server option/ip/dhcp-server/optionDHCP server option sets/ip/dhcp-server/option/setsDHCP relay/ip/dhcp-relayIP pool/ip/poolIP neighbors/ip/neighborIP neighbor discovery/ip/neighbor/discovery-settingsIP services/ip/serviceIP settings (forwarding)/ip/settingsIP proxy/ip/proxyIP proxy access list/ip/proxy/accessIP SOCKS/ip/socksIP SSH/ip/sshIP cloud/ip/cloudIP UPnP/ip/upnpIP UPnP interfaces/ip/upnp/interfacesIP SMB/ip/smbIP traffic flow/ip/traffic-flowIP traffic flow target/ip/traffic-flow/targetIP accounting/ip/accountingIP Kid Control/ip/kid-controlIP Kid Control devices/ip/kid-control/deviceIP Hotspot/ip/hotspotIP Hotspot profile/ip/hotspot/profileIP Hotspot user/ip/hotspot/userIP Hotspot user profile/ip/hotspot/user/profileIP Hotspot active/ip/hotspot/activeIP Hotspot host/ip/hotspot/hostIP Hotspot cookie/ip/hotspot/cookieIP Hotspot IP binding/ip/hotspot/ip-bindingIP Hotspot walled garden/ip/hotspot/walled-gardenIP Hotspot walled garden IP/ip/hotspot/walled-garden/ip
TaskResource PathFilter rules/ip/firewall/filterNAT rules/ip/firewall/natMangle rules/ip/firewall/mangleRAW rules/ip/firewall/rawAddress lists/ip/firewall/address-listConnections (conntrack)/ip/firewall/connectionConnection tracking/ip/firewall/connection/trackingService ports (ALGs)/ip/firewall/service-portLayer 7 protocols/ip/firewall/layer7-protocol
TaskResource PathIPv6 addresses/ipv6/addressIPv6 routes/ipv6/routeIPv6 firewall filter/ipv6/firewall/filterIPv6 firewall mangle/ipv6/firewall/mangleIPv6 firewall RAW/ipv6/firewall/rawIPv6 firewall address list/ipv6/firewall/address-listIPv6 ND (Neighbor Disc.)/ipv6/ndIPv6 ND prefix/ipv6/nd/prefixIPv6 DHCP client/ipv6/dhcp-clientIPv6 DHCP server/ipv6/dhcp-serverIPv6 pool/ipv6/poolIPv6 settings/ipv6/settings
TaskResource PathRouting tables/routing/tableRouting rules/routing/ruleOSPF instance/routing/ospf/instanceOSPF area/routing/ospf/areaOSPF interface template/routing/ospf/interface-templateOSPF neighbors/routing/ospf/neighborOSPF LSA/routing/ospf/lsaBGP connection/routing/bgp/connectionBGP template/routing/bgp/templateBGP session/routing/bgp/sessionBGP advertisements/routing/bgp/advertisementsBGP networks/routing/bgp/networkRIP instance/routing/rip/instanceRIP interface template/routing/rip/interface-templateRoute filter rules/routing/filter/ruleRoute filter select rules/routing/filter/select-rulePrefix lists/routing/filter/community-listBFD session/routing/bfd/sessionBFD configuration/routing/bfd/configurationRouting ID/routing/idRPKI/routing/rpkiIGMP Proxy/routing/igmp-proxyPIM/routing/pimsm
TaskResource PathPPP secrets/ppp/secretPPP profiles/ppp/profilePPP active connections/ppp/activePPP AAA settings/ppp/aaaPPP L2TP secret/ppp/l2tp-secret
TaskResource PathSimple queues/queue/simpleQueue tree/queue/treeQueue types/queue/typeInterface queues/queue/interface
TaskResource PathCAPsMAN manager/caps-man/managerCAPsMAN configuration/caps-man/configurationCAPsMAN channel/caps-man/channelCAPsMAN datapath/caps-man/datapathCAPsMAN security/caps-man/securityCAPsMAN provisioning/caps-man/provisioningCAPsMAN interface/caps-man/interfaceCAPsMAN registration table/caps-man/registration-tableCAPsMAN access list/caps-man/access-listCAPsMAN remote-cap/caps-man/remote-cap
TaskResource PathMPLS settings/mplsMPLS interface/mpls/interfaceMPLS forwarding table/mpls/forwarding-tableMPLS LDP/mpls/ldpMPLS LDP interface/mpls/ldp/interfaceMPLS LDP neighbor/mpls/ldp/neighborVPLS/interface/vplsTraffic engineering/mpls/traffic-eng
TaskResource PathPing/tool/ping (use call)Traceroute/tool/traceroute (use call)Bandwidth test/tool/bandwidth-test (use call)Torch (traffic by IP)/tool/torch (use call)Profile (CPU profile)/tool/profileNetwatch/tool/netwatchE-mail settings/tool/e-mailFetch (HTTP client)/tool/fetchGraphing interface/tool/graphing/interfaceGraphing resource/tool/graphing/resourceGraphing queue/tool/graphing/queueSniffer/tool/snifferSNMP/snmpMAC server/tool/mac-serverMAC Winbox/tool/mac-server/mac-winboxMAC Ping/tool/mac-server/pingBandwidth server/tool/bandwidth-serverIP Scan/tool/ip-scanSMS/tool/smsRomon/tool/romon
TaskResource PathContainer config/container/configContainers/containerContainer mounts/container/mountsContainer envs/container/envs
TaskResource PathIoT Bluetooth/iot/bluetoothIoT Bluetooth scanners/iot/bluetooth/scannersIoT GPIO/iot/gpioIoT MQTT broker/iot/mqtt/brokers
TaskResource PathZeroTier/zerotierZeroTier interface/zerotier/interface
python
resource = api.get_resource('/ip/firewall/filter')
rules = resource.get(chain='forward', action='drop')
python
resource = api.get_resource('/ip/firewall/filter')
resource.add(
chain='forward',
action='accept',
src_address='10.0.0.0/8',
place_before='*5' # Insert before rule *5
)
Note: Use underscores in Python for hyphenated attributes (e.g., src-address → src_address, place-before → place_before).
python
resource = api.get_resource('/ip/firewall/filter')
resource.call('move', {'numbers': '*A', 'destination': '*1'})
python
resource = api.get_resource('/ip/firewall/address-list')
ips = ['1.2.3.4', '5.6.7.8', '9.10.11.12']
for ip in ips:
resource.add(list='blocklist', address=ip, comment='Blocked via API')
python
resource = api.get_resource('/interface')
ifaces = resource.get(name='ether5')
if ifaces:
resource.set(id=ifaces[0]['id'], disabled='yes')
python
# The library always returns all properties; filter in Python:
resource = api.get_resource('/interface')
for iface in resource.get():
print(iface.get('name'), iface.get('type'), iface.get('running'))
python
# Tools that produce output need call() with parameters
resource = api.get_resource('/tool')
# Note: Some tools (ping, traceroute) run indefinitely.
# Use count parameter to limit.
result = resource.call('ping', {'address': '8.8.8.8', 'count': '4'})
for r in result:
print(r)
python
# Create a backup file
resource = api.get_resource('/system/backup')
resource.call('save', {'name': 'api-backup'})
# Export config to file
resource = api.get_resource('/')
resource.call('export', {'file': 'api-export'})
python
resource = api.get_resource('/system')
resource.call('reboot')
# resource.call('shutdown')
python
resource = api.get_resource('/system/package/update')
resource.call('check-for-updates')
result = resource.get()
print(result)
# resource.call('install') # Install and reboot
RouterOS 7.1+ also supports a REST API over HTTP/HTTPS. Use when the Python library is unavailable.
bash
# GET - Read resources
curl -k -u user:pass https://<IP>/rest/ip/address
# PUT - Create new entry
curl -k -u user:pass -X PUT https://<IP>/rest/ip/address \
--data '{"address":"192.168.1.1/24","interface":"ether1"}' \
-H "content-type: application/json"
# PATCH - Update entry
curl -k -u user:pass -X PATCH https://<IP>/rest/ip/address/*1 \
--data '{"comment":"updated"}' -H "content-type: application/json"
# DELETE - Remove entry
curl -k -u user:pass -X DELETE https://<IP>/rest/ip/address/*1
# POST - Run any command
curl -k -u user:pass -X POST https://<IP>/rest/ip/address/print \
--data '{"_proplist":["address","interface"]}' \
-H "content-type: application/json"
bash
curl -k -u user:pass -X POST https://<IP>/rest/interface/print \
--data '{".query":["type=ether"],"_proplist":["name","type","running"]}' \
-H "content-type: application/json"
python
import requests
from requests.auth import HTTPBasicAuth
base = 'https://<IP>/rest'
auth = HTTPBasicAuth('<USER>', '<PASS>')
# GET all interfaces
r = requests.get(f'{base}/interface', auth=auth, verify=False)
print(r.json())
# POST (run commands with parameters)
r = requests.post(f'{base}/ip/address/print',
auth=auth, verify=False,
json={'_proplist': ['address', 'interface']})
print(r.json())
python
import routeros_api
from routeros_api.exceptions import RouterOsApiCommunicationError
try:
conn = routeros_api.RouterOsApiPool(host, username=user, password=pw, plaintext_login=True)
api = conn.get_api()
resource = api.get_resource('/ip/address')
resource.add(address='invalid', interface='nonexistent')
except RouterOsApiCommunicationError as e:
print(f"API Error: {e}")
except ConnectionError:
print("Cannot reach router")
finally:
try:
conn.disconnect()
except:
pass
CodeMeaning0Missing item or command1Argument value failure2Command interrupted3Scripting related failure4General failure5API related failure6TTY related failure7Value from :return command
id field in responses (e.g., *1, *A) is the internal MikroTik ID used for set/remove.src-address → src_address.place_before when adding to control position./routing/ospf/instance not /routing/ospf)./ip/service enable api.count or duration parameter.www or www-ssl service enabled on the router.count, duration, once).