Mikrotik Api Examples |link| [FAST]
Enter the .
/ip service enable api /ip service set api port=8728 # Default port, change for security /ip service set api address=192.168.88.0/24 # Restrict access For encrypted communication (recommended over the internet), use on port 8729.
if == ' main ': main() Use Case 2: Auto-Ban SSH Brute Force Attempts Read failed login attempts from logs and add source IPs to an address list. mikrotik api examples
Installation:
For network engineers and system administrators, managing a fleet of MikroTik routers (RouterOS) via the graphical WinBox or WebFig interface is efficient for one-off tasks. However, when you need to provision 100 routers, dynamically update firewall filters based on an external threat feed, or automate bandwidth changes based on the time of day, the command-line interface (CLI) and GUI fall short. Enter the
The examples provided—covering Python, authentication, firewall rules, queues, monitoring, and real-world use cases—should serve as a solid foundation for your automation projects. Start small: write a script to back up your config via API, then expand to dynamic firewalls or scheduled bandwidth changes.
print(f"Added lease with .id {lease['.id']}") Limit a specific IP to 5Mbps download / 2Mbps upload. Start small: write a script to back up
api = librouteros.connect(...) address_list = api.path('ip', 'firewall', 'address-list') 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") Use Case 3: Bandwidth Time-of-Day Scheduler Change queue max-limit at 9 AM and 6 PM.