Mikrotik Api Examples -
The traditional API uses a custom socket-based protocol. Python is commonly used to interact with this. Python Example: Retrieving Resource Info
Sometimes, if you send a malformed query or the buffer overflows, the socket simply drops. You don't always get a nice error message; the connection just dies. Debugging these disconnections can be maddening, especially over high-latency links.
api.send(cmd='/interface/print', tag='iface') api.send(cmd='/ip/address/print', tag='addr') api.send(cmd='/system/resource/print', tag='res')
In this example, we'll create a new user using the Mikrotik API in PHP. mikrotik api examples
: By default, the API uses port 8728 for unencrypted traffic and 8729 for API over SSL (highly recommended for production).
/ip/firewall/filter/print /ip/firewall/filter/add =chain=input =src-address=203.0.113.0/24 =action=drop /ip/firewall/filter/set =.id=*1 =disabled=yes
import datetime, time
if ($result) echo 'User created successfully'; else echo 'Error creating user';
| Query | Description | |-------|-------------| | ?name | True if item has property 'name' | | ?-name | True if item does NOT have property 'name' | | ?name=x | True if property 'name' equals 'x' | | ?<name=x | True if property 'name' is less than 'x' | | ?>name=x | True if property 'name' is greater than 'x' |
To help me tailor the next step for your project, let me know: The traditional API uses a custom socket-based protocol
logs = api.path('log').select('time', 'message') for log in logs: if 'ssh' in log['message'].lower() and 'failure' in log['message'].lower(): # Extract IP using regex (pseudo) import re match = re.search(r'from (\d+.\d+.\d+.\d+)', log['message']) if match: ip = match.group(1) # Check if already listed existing = list(address_list.select(list='ssh_block', address=ip)) if not existing: address_list.add(list='ssh_block', address=ip, timeout='1h') print(f"Banned ip for 1 hour")
Python is the preferred language for network automation. The routeros-api library on PyPI makes interaction simple. Prerequisite: Install Library pip install routeros-api Use code with caution. Example A: Connecting and Printing Interface Stats This script connects to a router and lists all interfaces.
Connect to your router via SSH or the WinBox terminal and run the following commands: You don't always get a nice error message;
