Mikrotik Api Examples
: Connection requires valid RouterOS credentials. RouterOS v6 utilizes a two-step challenge-response authentication, while RouterOS v7 simplifies this with a direct login flow. Enabling the API on RouterOS
The REST API shares the same service port as the secure web interface ( www-ssl ).
The MikroTik API typically runs on TCP port 8728 (or 8729 for SSL). Unlike a standard shell, the API uses a specific sentence-based protocol. mikrotik api examples
# Create a custom group with API permissions /user group add name=api-group policy=api,read,write,!local,!telnet,!ssh,!ftp,winbox,!web # Add a user to the new group /user add name=api_user group=api-group password=YourSecurePassword123! Use code with caution. 2. Understanding the API Protocol Basics
def remove_firewall_rule_by_comment(self, comment_pattern): """Remove firewall rules containing specific comment text""" url = f"self.base_url/ip/firewall/filter" response = requests.get(url, auth=self.auth, verify=self.verify_ssl) if response.status_code == 200: rules = response.json() for rule in rules: if "comment" in rule and comment_pattern in rule["comment"]: delete_url = f"url/rule['.id']" requests.delete(delete_url, auth=self.auth, verify=self.verify_ssl) logging.info(f"Removed rule: rule['.id']") : Connection requires valid RouterOS credentials
In this example, we'll use Python to retrieve basic device information using the Mikrotik API.
import routeros_api def get_system_resources(host, username, password): # Establish connection connection = routeros_api.RouterOsApiPool( host, username=username, password=password, plaintext_login=True ) api = connection.get_api() # Navigate to the resource menu resources = api.get_resource('/system/resource') data = resources.get() # Extract and format metrics for item in data: print(f"Device Model: item.get('board-name')") print(f"RouterOS Version: item.get('version')") print(f"CPU Load: item.get('cpu-load')%") print(f"Free Memory: int(item.get('free-memory')) / 1024 / 1024:.2f MB") connection.disconnect() # Usage get_system_resources('192.168.88.1', 'admin', 'YourSecurePassword') Use code with caution. Example 2: Adding a Static DHCP Lease The MikroTik API typically runs on TCP port
: Always use port 8729 (API-SSL) in production environments. Generate or import a trusted SSL certificate onto your MikroTik router to prevent man-in-the-middle attacks.
The API is frequently used to bridge the gap between MikroTik routers and web-based billing systems.
This public link is valid for 7 days and shares a thread, including any personal information you added. This link or copies made by others cannot be deleted. If you share with third parties, their policies apply. Can’t copy the link right now. Try again later.
: If your script does not explicitly close connections inside a try/finally block, the router will eventually hit its max concurrent API session limit. You can monitor and terminate dead sessions inside RouterOS via /user active print .