Examples 2021 - Mikrotik Api
Read failed login attempts from logs and add source IPs to an address list.
import requests from requests.auth import HTTPBasicAuth def add_ip_to_blacklist(host, username, password, ip_address): url = f"https://host/rest/ip/firewall/address-list" payload = "list": "Blacklist_API", "address": ip_address, "comment": "Added via Python REST API" # RouterOS uses basic authentication over HTTPS response = requests.put( url, json=payload, auth=HTTPBasicAuth(username, password), verify=False # Set to True if using a valid SSL cert ) if response.status_code == 201 or response.status_code == 200: print(f"Successfully added ip_address to the blacklist.") else: print(f"Failed to add IP. Error: response.text") # Usage add_ip_to_blacklist('192.168.88.1', 'admin', 'YourSecurePassword', '10.0.0.55') Use code with caution. 4. PHP MikroTik API Examples
: By default, the API uses port 8728 for unencrypted traffic and 8729 for API over SSL (highly recommended for production). mikrotik api examples
'192.168.88.1', 'user' => 'admin', 'pass' => 'YourSecurePassword' ]); // Build the query to print active hotspot users $query = new Query('/ip/hotspot/active/print'); $responses = $client->query($query)->read(); echo "
Instead of running a broad /ip/arp/print , use API queries to filter data on the router side (e.g., ?address=192.168.88.254 ) to save bandwidth and memory. Read failed login attempts from logs and add
def block_ip_address(ip_address, comment="Blocked by API"): url = f"router_ip/ip/firewall/filter" payload = "chain": "forward", "src-address": ip_address, "action": "drop", "comment": comment
// Query all interfaces $query = new Query('/interface/print'); $interfaces = $client->query($query)->read(); print_r($interfaces); $interfaces = $client->
import routeros_api def get_router_ips(host, username, password): # Establish connection connection = routeros_api.RouterOsApiPool( host, username=username, password=password, plaintext_login=True ) api = connection.get_api() # Navigate to the IP address resource path ip_resource = api.get_resource('/ip/address') addresses = ip_resource.get() # Parse and print results for addr in addresses: print(f"Interface: addr['interface'] | IP: addr['address'] | Network: addr['network']") connection.disconnect() # Usage get_router_ips('192.168.88.1', 'admin', 'YourSecurePassword') Use code with caution. Example 2: Adding a Firewall Rule
#!/bin/bash HOST="192.168.88.1" USER="admin" PASS="" PORT=8729
B) Using librouteros for binary API (v6/v7)