### Additional Example: Firewall Address List Source: https://github.com/socialwifi/routeros-api/wiki/How-to-use An end-to-end example demonstrating the usage of add, get, and remove operations on the IP firewall address list resource. ```APIDOC ### Other Example: `list_address = api.get_resource('/ip/firewall/address-list')` `list_address.add(address="192.168.0.1",comment="P1",list="10M")` `list_address.get(comment="P1")` `list_address.remove(id="*7")` ``` -------------------------------- ### Install using pip Source: https://github.com/socialwifi/routeros-api/wiki/Installation Use this command to install the routeros-api library via pip. ```bash pip install routeros-api ``` -------------------------------- ### Install routeros-api Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/README.md Import the library to begin using its functionalities. ```python import routeros_api ``` -------------------------------- ### ResponsePromise get() Method Example Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/async-support.md Demonstrates how to initiate an asynchronous API call and then blockingly retrieve the response using the .get() method. This is useful when you need to perform other tasks while waiting for the API response. ```python api = pool.get_api() queues = api.get_resource('/queue/simple') # Non-blocking: returns immediately promise = queues.call_async('print') # Do other work... print("Waiting for response...") # Blocking: wait for response result = promise.get() print(f"Got {len(result)} queues") ``` -------------------------------- ### Custom Command (Ping) Response Example Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/response-format.md Provides an example of the response structure for a custom command like 'ping'. It includes details for each ping attempt. ```python response = api.get_resource('/').call('ping', {'address': '8.8.8.8', 'count': '2'}) # Response structure [ {'seq': '0', 'host': '8.8.8.8', 'time': '14ms', ...}, {'seq': '1', 'host': '8.8.8.8', 'time': '15ms', ...}, ] # done_message: {} ``` -------------------------------- ### Add, Get, and Remove Firewall Address List Entry Source: https://github.com/socialwifi/routeros-api/blob/master/README.md This example demonstrates the full lifecycle of managing an entry in the firewall address list: adding it, retrieving it, and then removing it. ```python list_address = api.get_resource('/ip/firewall/address-list') list_address.add(address='192.168.0.1', comment='P1', list='10M') response = list_address.get(comment='P1') list_address.remove(id=response[0]['id']) ``` -------------------------------- ### Simple Query Example Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/router-os-resource.md Demonstrates fetching DHCP leases based on a specific server name using `call`. ```python # Get DHCP leases where server='developers' resource = api.get_resource('/ip/dhcp-server/lease') result = resource.call('print', {}, {'server': 'developers'}) ``` -------------------------------- ### Command with Arguments Example Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/router-os-resource.md Shows how to execute commands like 'fetch' with URL and destination path, or 'monitor' with specific flags. ```python # Run fetch command tool = api.get_resource('/tool') response = tool.call('fetch', {'url': 'http://example.com', 'dst-path': 'output.html'}) # Monitor interface with once flag iface = api.get_resource('/interface/ether/poe') response = iface.call('monitor', {'numbers': '0', 'once': None}) ``` -------------------------------- ### Minimal RouterOS API Setup Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/module-reference.md Establishes a basic connection to a RouterOS device using the RouterOsApiPool. ```python import routeros_api pool = routeros_api.RouterOsApiPool('192.168.1.1') api = pool.get_api() ``` -------------------------------- ### Instantiate RouterOsBinaryResource Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/router-os-binary-resource.md Demonstrates how to get a binary resource instance. Direct instantiation is not recommended; use RouterOsApi.get_binary_resource() instead. ```python api = pool.get_api() resource = api.get_binary_resource('/queue/simple') ``` -------------------------------- ### Simple Iteration Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/response-format.md Demonstrates how to iterate through a list of resources returned by a GET request. ```APIDOC ## Simple Iteration ### Description Iterate through a list of resources returned by a GET request. ### Method GET ### Endpoint `/interface` ### Parameters None ### Request Example ```python response = api.get_resource('/interface').get() ``` ### Response #### Success Response A list of interface objects. #### Response Example ```python # Example structure of a single interface object: { "name": "ether1", "mac-address": "AA:BB:CC:DD:EE:FF", "type": "ethernet" } ``` ### Usage ```python response = api.get_resource('/interface').get() for interface in response: print(interface['name']) ``` ``` -------------------------------- ### Ping an IP Address Source: https://github.com/socialwifi/routeros-api/blob/master/README.md This example shows how to ping a specified IP address a certain number of times and retrieve the results. ```python >>> api.get_resource('/').call('ping', {'address': '8.8.8.8', 'count': '4'}) ``` -------------------------------- ### Add Command Response Example Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/response-format.md Illustrates the response after adding a new resource. It typically returns a list containing the ID of the newly created item. ```python response = api.get_resource('/queue/simple').add(name='test') # Response structure [ {'id': '*5'}, # ID of newly created item ] # done_message: {} ``` -------------------------------- ### Print (List) Response Example Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/response-format.md Shows the typical response structure when listing resources, such as queues. Each item in the list represents a resource with its properties. ```python response = api.get_resource('/queue/simple').get() # Response structure [ {'id': '*1', 'name': 'queue1', 'target': '192.168.1.0/24'}, {'id': '*2', 'name': 'queue2', 'target': '192.168.2.0/24'}, ] # done_message: {} ``` -------------------------------- ### Count Only Example Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/router-os-resource.md Demonstrates retrieving only the count of matching records using the `count-only` argument. ```python # Get count of static routes resource = api.get_resource('/ip/route') response = resource.call('print', {'count-only': None}) count = response.done_message.get('ret') ``` -------------------------------- ### Get Element Source: https://github.com/socialwifi/routeros-api/wiki/How-to-use Demonstrates how to retrieve a specific element from a resource list by providing an attribute and its value. ```APIDOC ## Get element: `list.get(attribute=value)` ### Example: `list_queues.get(name="jhon")` ``` -------------------------------- ### get Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/router-os-binary-resource.md Retrieves all items from the resource, optionally filtering. All values are raw bytes. ```APIDOC ## get ### Description Retrieves all items from the resource, optionally filtering. All values are raw bytes. ### Method GET ### Endpoint [Resource Path] ### Parameters #### Query Parameters - **kwargs** (bytes) - Optional - Query filters as keyword arguments. All values must be bytes or will be logged with warning and auto-encoded. ### Response #### Success Response (200) - **AsynchronousResponse** - List of dicts with bytes keys/values ### Request Example ```python # Assuming api and resource are already initialized # resource = api.get_binary_resource('/queue/simple') result = resource.get() for item in result: print(item[b'name']) # bytes print(item[b'max-limit']) # bytes ``` ``` -------------------------------- ### Set Command Response Example Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/response-format.md Shows the response for a 'set' operation, which modifies an existing resource. This operation usually returns an empty list as it does not return data. ```python response = api.get_resource('/queue/simple').set(id='*1', name='updated') # Response structure [] # Empty list (set returns no data) # done_message: {} ``` -------------------------------- ### get Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/router-os-resource.md Retrieves all items from the resource, optionally filtering by attributes. Query filters are passed as keyword arguments. ```APIDOC ## get(**kwargs) ### Description Retrieves all items from the resource, optionally filtering by attributes. Keys correspond to API attribute names. Attributes with dashes use underscores (e.g., `max_limit` becomes `max-limit`). ### Method GET ### Endpoint /{resource_path} ### Parameters #### Query Parameters - **kwargs** (dict) - Optional - Query filters as keyword arguments. ### Response #### Success Response (200) - **AsynchronousResponse** - List-like response with `.done_message` attribute containing metadata and `.done` flag. ### Request Example ```python api = pool.get_api() queues = api.get_resource('/queue/simple') # Get all queues all_queues = queues.get() # Get queues with specific target filtered = queues.get(target='192.168.1.0/24') # Access done message result = queues.get() print(result.done_message) ``` ``` -------------------------------- ### Remove Command Response Example Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/response-format.md Details the response after removing a resource. Similar to the 'set' operation, it returns an empty list. ```python response = api.get_resource('/queue/simple').remove(id='*1') # Response structure [] # Empty list (remove returns no data) # done_message: {} ``` -------------------------------- ### Custom Command (Script Run) Response Example Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/response-format.md Shows the response for running a script via the API. The script's output is typically found in the 'done_message'. ```python response = api.get_resource('/system/script').call('run', {'number': '0'}) # Response structure [] # Empty list (script output in done_message) # done_message: {b'ret': b'Script output here'} ``` -------------------------------- ### Full-Featured RouterOS API Connection and Query Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/module-reference.md Demonstrates a full setup including custom data structures, resource definition, and complex query execution with filters. ```python import routeros_api from routeros_api import query, api_structure from routeros_api.exceptions import RouterOsApiConnectionError import collections # Connection pool = routeros_api.RouterOsApiPool('192.168.1.1') api = pool.get_api() # Custom structure structure = collections.defaultdict( lambda: api_structure.StringField() ) structure['disabled'] = api_structure.BooleanField() # Resource with queries resource = api.get_resource('/queue/simple', structure=structure) # Complex query result = resource.call( 'print', {}, {}, additional_queries=( query.AndQuery( query.IsEqualQuery('disabled', 'no'), query.IsGreaterQuery('max-limit', '1000000'), ), ) ) ``` -------------------------------- ### Get All Queues Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/router-os-resource.md Retrieves all items from the resource. Use keyword arguments for filtering. ```python api = pool.get_api() queues = api.get_resource('/queue/simple') # Get all queues all_queues = queues.get() ``` -------------------------------- ### Async Response Buffering Example Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/async-support.md Illustrates the internal buffer tracking multiple asynchronous responses, showing the lifecycle of promises from waiting to response reception and iteration. ```text Promise 1 (tag='1') → [waiting] → [response received] → [iteration] Promise 2 (tag='2') → [waiting] → [response received] → [iteration] Promise 3 (tag='3') → [waiting] → [response received] → [iteration] ``` -------------------------------- ### Get Detailed Queue Information Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/router-os-resource.md Retrieves all items with detailed information, equivalent to the CLI 'print detail' command. ```python queues = api.get_resource('/queue/simple') detailed = queues.detailed_get() ``` -------------------------------- ### RouterOS API Key Transformation Example Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/router-os-resource.md Illustrates the automatic transformation of underscore notation in Python parameter names to dash notation used by the MikroTik API. This allows for more Pythonic parameter naming while ensuring compatibility with the API. ```python # These are equivalent: queues.set(id='*2', max_limit='1M') # Python style with underscore queues.set(id='*2', **{'max-limit': '1M'}) # Raw MikroTik style ``` -------------------------------- ### Run a System Script and Get Output Source: https://github.com/socialwifi/routeros-api/blob/master/README.md Execute a script on the RouterOS device and capture its output. The script source is retrieved first, then executed. ```python >>> api.get_resource('/system/script').get()[0]['source'] '/put "hello"' >>> response = api.get_resource('/system/script').call('run', {'number': '0'}) >>> response.done True >>> response.done_message['ret'] 'hello' ``` -------------------------------- ### IsEqualQuery Example Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/query.md Shows how to use IsEqualQuery to match items where an attribute equals a specific value. This can be done using a dictionary for simple equality or an explicit IsEqualQuery object for more complex scenarios. ```python from routeros_api import query resource = api.get_resource('/queue/simple') # Equivalent ways: # 1. Using dict (auto-converted to IsEqualQuery) response = resource.call('print', {}, {'disabled': 'no'}) # 2. Using explicit query object response = resource.call( 'print', {}, {}, additional_queries=(query.IsEqualQuery('disabled', 'no'),) ) ``` -------------------------------- ### Connect to Production Environment with Signed Cert Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/configuration.md This configuration is for production environments using SSL with a signed certificate. Ensure the CA bundle path is correct and the password is provided securely, for example, via an environment variable. ```python import ssl ssl_context = ssl.create_default_context() ssl_context.load_verify_locations('/etc/ssl/certs/ca-bundle.crt') pool = routeros_api.RouterOsApiPool( 'router.example.com', username='api_user', password=os.getenv('ROUTEROS_PASSWORD'), plaintext_login=True, ssl_context=ssl_context ) api = pool.get_api() ``` -------------------------------- ### Custom Exception Handler Example Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/api-communicator.md Demonstrates how to define and register a custom exception handler to manage specific RouterOS API errors. ```python class CustomExceptionHandler: def handle(self, exception): if isinstance(exception, RouterOsApiConnectionError): # Custom handling raise CustomError("Connection lost") from exception pool = routeros_api.RouterOsApiPool('192.168.1.1') api = pool.get_api() # Access internal communicator through pool's setup # (This is typically done automatically by RouterOsApiPool) # api.communicator.add_exception_handler(CustomExceptionHandler()) ``` -------------------------------- ### Python OrQuery Example Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/query.md Use OrQuery to combine multiple query conditions with a logical OR. This allows finding items that satisfy at least one of the specified criteria. ```python from routeros_api import query # Find disabled queues OR queues with max-limit > 10M queues = api.get_resource('/queue/simple') response = queues.call( 'print', {}, {}, additional_queries=( query.OrQuery( query.IsEqualQuery('disabled', 'yes'), query.IsGreaterQuery('max-limit', '10000000'), ), ) ) # Find static routes OR routes to 10.0.0.0/8 routes = api.get_resource('/ip/route') response = routes.call( 'print', {}, {}, additional_queries=( query.OrQuery( query.HasValueQuery('static'), query.IsEqualQuery('dst-address', '10.0.0.0/8'), ), ) ) ``` -------------------------------- ### IpNetworkField Usage Example Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/types.md Demonstrates how to use IpNetworkField to send and receive ipaddress objects for network addresses. Requires importing ipaddress and the custom field. ```python import collections import ipaddress from routeros_api.api_structure import IpNetworkField structure = collections.defaultdict(lambda: StringField()) structure['network'] = IpNetworkField() resource = api.get_resource('/ip/firewall/address-list', structure=structure) # Send with ipaddress object resource.add( list='office_nets', address=ipaddress.ip_network('10.0.0.0/8') ) # Receive as ipaddress object lists = resource.get() for item in lists: network = item['network'] # ipaddress.ip_network object print(network.network_address) print(network.netmask) ``` -------------------------------- ### Connect to Legacy RouterOS with Challenge-Response Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/configuration.md Use this for older RouterOS versions that require MD5 challenge-response authentication instead of plaintext login. SSL is disabled in this example. ```python pool = routeros_api.RouterOsApiPool( '10.0.0.1', username='admin', password='admin', plaintext_login=False, # Use MD5 challenge-response use_ssl=False ) api = pool.get_api() ``` -------------------------------- ### Basic RouterOS Resource Access Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/router-os-api.md Shows how to get a resource for simple queues, retrieve them, add a new one, and update an existing one using the API. ```python api = pool.get_api() # Get list of simple queues queues_resource = api.get_resource('/queue/simple') queues = queues_resource.get() # Returns list of dicts with auto-typed values # Add a queue queues_resource.add(name='queue1', max_limit='512k/4M', target='192.168.1.0/24') # Update a queue queues_resource.set(id='*2', name='updated_queue') ``` -------------------------------- ### Print with Count-Only Response Example Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/response-format.md Demonstrates the response for a 'count-only' print operation, which returns an empty list and the total count in the 'done_message'. ```python response = api.get_resource('/ip/dhcp-server/lease').call('print', {'count-only': None}) # Response structure [] # Empty list # done_message: {b'ret': b'42'} ``` -------------------------------- ### Handling Multiple Response Types Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/response-format.md Explains the different response structures returned by various API commands like GET, SET, ADD, and COUNT. ```APIDOC ## Handling Multiple Response Types ### Description Different API commands return distinct response structures. This section outlines the expected output for common operations like GET, SET, ADD, and COUNT. ### Methods and Response Types - **GET** - **Description**: Retrieves a list of items. - **Response Structure**: `[item, item, item]` - **Example**: `api.get_resource('/queue/simple').get()` - **SET** - **Description**: Modifies existing items. Typically returns an empty list upon success. - **Response Structure**: `[]` - **Example**: `api.get_resource('/queue/simple').set(id='*1')` - **ADD** - **Description**: Adds a new item. Returns a list containing the ID of the newly added item. - **Response Structure**: `[{'id': 'new_id'}]` - **Example**: `api.get_resource('/queue/simple').add(name='new')` - **CALL (with specific options like count-only)** - **Description**: Executes a command, potentially with options like `count-only`. The result might be in the `done_message`. - **Response Structure**: `[]` (for the main response body), with result in `done_message`. - **Example**: `api.get_resource('/queue/simple').call('print', {'count-only': None})` - **Done Message Example**: `{b'ret': b'42'}` ``` -------------------------------- ### RouterOS API Type Conversion Example Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/router-os-resource.md Demonstrates how to define a custom type structure for API resource parameters and responses, enabling automatic conversion between Python types and MikroTik wire formats. Use this to ensure correct data types for fields like bandwidth limits, booleans, and integers. ```python import collections from routeros_api.api_structure import IntegerField, BooleanField, StringField # Define type structure structure = collections.defaultdict(lambda: StringField()) structure['max-limit'] = StringField() # Keep as string for bandwidth limits structure['disabled'] = BooleanField() # Convert to/from bool structure['packets'] = IntegerField() # Convert to/from int resource = api.get_resource('/queue/simple', structure=structure) # Call with Python types resource.add( name='my_queue', disabled=False, packets=1000 ) # Results come back as Python types data = resource.get() for item in data: print(f"Disabled: {item['disabled']} (type: {type(item['disabled'])})") print(f"Packets: {item['packets']} (type: {type(item['packets'])})") ``` -------------------------------- ### ResponsePromise Iteration Example Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/async-support.md Shows how to iterate over response items from an asynchronous API call as they arrive. This method blocks on each iteration if the buffer is empty, automatically fetches more data, and stops when the response is complete. ```python promise = api.get_resource('/queue/simple').call_async('print') # Iterate as data arrives for queue in promise: print(f"Queue: {queue['name']}") ``` -------------------------------- ### Get All Queues with Bytes Values Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/router-os-binary-resource.md Retrieves all items from a binary resource endpoint. All values in the result are raw bytes, requiring explicit handling. ```python result = resource.get() # Access bytes values for item in result: print(item[b'name']) # bytes print(item[b'max-limit']) # bytes ``` -------------------------------- ### Load All API Response Data (High Memory) Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/response-format.md Example of loading an entire API response into memory, suitable for smaller datasets but potentially memory-intensive. ```python # Load all at once (high memory) all_leases = api.get_resource('/ip/dhcp-server/lease').get() print(f"Total: {len(all_leases)}") ``` -------------------------------- ### Complete Structure Example for NAT Resource Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/types.md Defines a comprehensive structure for the `/ip/firewall/nat` resource, mapping various fields to their appropriate types such as Boolean, Integer, Timedelta, and IpNetwork. This ensures type-correct access when retrieving and processing NAT rules. ```python import collections import datetime import ipaddress from routeros_api.api_structure import ( StringField, BooleanField, IntegerField, TimedeltaField, IpNetworkField, ListField, ) # Define structure for /ip/firewall/nat resource nat_structure = collections.defaultdict(lambda: StringField()) nat_structure['enabled'] = BooleanField() nat_structure['to-ports'] = IntegerField() nat_structure['timeout'] = TimedeltaField() nat_structure['src-address'] = IpNetworkField() nat_structure['protocol'] = StringField() api = pool.get_api() nat_resource = api.get_resource('/ip/firewall/nat', structure=nat_structure) # Now all operations use correct types rules = nat_resource.get() for rule in rules: # Type-correct access if not rule['enabled']: continue if rule['to-ports'] > 1024: print(f"Port: {rule['to-ports']} (type: int)") ``` -------------------------------- ### Handling Different API Response Structures Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/response-format.md Illustrates the varied response structures returned by different types of API calls (GET, SET, ADD, COUNT). ```python # GET returns list of items get_response = api.get_resource('/queue/simple').get() # [item, item, item] # SET returns empty set_response = api.get_resource('/queue/simple').set(id='*1') # [] # ADD returns item with ID add_response = api.get_resource('/queue/simple').add(name='new') # [{'id': '*5'}] # COUNT returns value in done_message count_response = api.get_resource('/queue/simple').call('print', {'count-only': None}) # [] # done_message: {b'ret': b'42'} ``` -------------------------------- ### Using SSL Source: https://github.com/socialwifi/routeros-api/wiki/How-to-use Demonstrates how to enable and configure SSL for secure connections to RouterOS devices. ```APIDOC ## Using SSL If we want to use SSL, we can simply specify use_ssl as true: `connection = routeros_api.RouterOsApiPool('', username='admin', password='', use_ssl=True)` This will automatically verify SSL certificate and hostname. The most flexible way to modify SSL parameters is to provide an SSL Context object using the ssl_context parameter, but for typical use-cases with self-signed certificates, the shorthand options of ssl_verify and ssl_verify_hostname are provided. e.g. if using a self-signed certificate, you can (but probably shouldn't) use: `connection = routeros_api.RouterOsApiPool('', username='admin', password='', use_ssl=True, ssl_verify=False, ssl_verify_hostname=False)` ``` -------------------------------- ### Get Route Count with Boolean Filter Source: https://github.com/socialwifi/routeros-api/blob/master/README.md Demonstrates how to get the count of routes that meet a boolean condition, such as being static. ```python >>> api.get_resource('/ip/route').call('print', {'count-only': None}, {'static': 'yes'}).done_message ``` -------------------------------- ### ListField Usage Example Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/types.md Shows how to use ListField with different subfield types (StringField, IntegerField) to handle lists of data. It illustrates sending and receiving comma or semicolon-separated values. ```python import collections from routeros_api.api_structure import ListField, StringField, IntegerField structure = collections.defaultdict(lambda: StringField()) structure['addresses'] = ListField(StringField()) structure['ports'] = ListField(IntegerField()) resource = api.get_resource('/ip/firewall/filter', structure=structure) # Send list resource.add( chain='input', addresses=['192.168.1.1', '192.168.1.2'], ports=[80, 443] ) # Receive as list rules = resource.get() for rule in rules: print(rule['addresses']) # ['192.168.1.1', '192.168.1.2'] print(rule['ports']) # [80, 443] ``` -------------------------------- ### Get Resource List Source: https://github.com/socialwifi/routeros-api/wiki/How-to-use Retrieves a resource object that allows for further operations like getting, adding, or removing elements. ```python list = api.get_resource('/command') ``` ```python list_queues = api.get_resource('/queue/simple') ``` -------------------------------- ### RouterOS Binary Resource Usage Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/router-os-api.md Provides examples of using get_binary_resource to obtain raw bytes responses for API calls, including debugging and manual bytes handling for commands like 'ping' and 'fetch'. ```python api = pool.get_api() # Get raw bytes response (useful for debugging or binary-safe operations) raw_response = api.get_binary_resource('/').call('ping', {'address': '8.8.8.8'}) # Manual bytes handling for commands resource = api.get_binary_resource('/tool') response = resource.call('fetch', {b'url': b'http://example.com', b'dst-path': b'output.html'}) ``` -------------------------------- ### ApiCommunicator Call Example Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/api-communicator.md Example of using the call method to retrieve queue simple print data with a filter. The communicator handles encoding, exceptions, parsing, and async wrapping. ```python api = pool.get_api() # Internally calls communicator.call() result = api.get_resource('/queue/simple').call('print', {}, {'name': 'office'}) # The communicator handles: # 1. String → bytes encoding # 2. Exception wrapping # 3. Response parsing # 4. Async promise wrapping ``` -------------------------------- ### get_async Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/router-os-binary-resource.md Asynchronous variant of get(). Returns a promise. ```APIDOC ## get_async ### Description Asynchronous variant of `get()`. Returns a promise. ### Method GET (async) ### Endpoint [Resource Path] ### Parameters #### Query Parameters - **kwargs** (bytes) - Optional - Query filters as keyword arguments. All values must be bytes or will be logged with warning and auto-encoded. ### Response #### Success Response (200) - **ResponsePromise** - Promise object ``` -------------------------------- ### Fetch List/Resource Source: https://github.com/socialwifi/routeros-api/wiki/How-to-use Demonstrates how to retrieve a resource collection using `get_resource` and then fetch all elements within that resource. ```APIDOC ## Fetch List/Resource `list = api.get_resource('/command') ` ### Example `list_queues = api.get_resource('/queue/simple') ` ### Show all elements `list_queues.get()` ``` -------------------------------- ### Execute a Generic Resource Command Source: https://github.com/socialwifi/routeros-api/blob/master/README.md Use this to call any resource with parameters. For binary data, use `get_binary_resource`. ```python api.get_resource('/').call('', { }) ``` ```python api.get_binary_resource('/').call('', { }) ``` -------------------------------- ### Get New Item ID Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/router-os-resource.md Retrieves the ID of a newly created item from the response object. ```python new_id = response[0].get('id') if response else None ``` -------------------------------- ### Establish a basic connection Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/README.md Create a connection pool to a RouterOS device using provided credentials. ```python pool = routeros_api.RouterOsApiPool('192.168.1.1', username='admin', password='admin') api = pool.get_api() ``` -------------------------------- ### Get Specific Element by Attribute Source: https://github.com/socialwifi/routeros-api/wiki/How-to-use Retrieves a specific element from a resource list based on one of its attributes. ```python list.get(attribute=value) ``` ```python list_queues.get(name="jhon") ``` ```python list_address.get(comment="P1") ``` -------------------------------- ### Handle RouterOsApiFatalCommunicationError Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/errors.md Example of catching RouterOsApiFatalCommunicationError, indicating a fatal error occurred and the connection needs to be re-established. ```python from routeros_api.exceptions import RouterOsApiFatalCommunicationError try: api.get_resource('/').get() except RouterOsApiFatalCommunicationError as e: print(f"Fatal RouterOS error, reconnecting required: {e}") # Connection is now closed, must call RouterOsApiPool.disconnect() # and reconnect with pool.get_api() ``` -------------------------------- ### Retrieving Script Output from 'done_message' Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/response-format.md Demonstrates how to get the return value of a script execution from the 'ret' key in the done_message. ```python response = api.get_resource('/system/script').call('run', {'number': '0'}) # Get script return value script_output = response.done_message[b'ret'].decode() print(f"Script output: {script_output}") ``` -------------------------------- ### Login with Binary Resource Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/router-os-binary-resource.md Demonstrates how the login process internally uses a binary resource to handle bytes directly. This is typically handled automatically by RouterOsApi.login(). ```python api = pool.get_api() # Internally, the login process uses binary resource: # binary_resource = api.get_binary_resource('/') # binary_resource.call('login', ...) # Handles bytes directly ``` -------------------------------- ### Get Queues Asynchronously Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/router-os-resource.md Initiates an asynchronous retrieval of items. Call .get() on the returned promise to retrieve results. ```python promise = queues.get_async() # ... do other work ... results = promise.get() # Blocks until response received ``` -------------------------------- ### Get Filtered Queues Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/router-os-resource.md Retrieves items from the resource, filtering by specified attributes. Attributes with dashes use underscores. ```python filtered = queues.get(target='192.168.1.0/24') ``` -------------------------------- ### Show All Elements in Resource Source: https://github.com/socialwifi/routeros-api/wiki/How-to-use Fetches and displays all elements within a given resource list. ```python list_queues.get() ``` -------------------------------- ### Execute Commands Source: https://github.com/socialwifi/routeros-api/wiki/How-to-use Shows how to execute arbitrary RouterOS commands using the `call` method on a binary resource. ```APIDOC ## Execute Commands `api.get_binary_resource('/').call('',{ })` Call this with a resource and parameters as name/value pairs. ### Examples `api.get_binary_resource('/').call('tool/fetch',{ 'url': "https://dummy.url" })` `api.get_binary_resource('/').call('ping', { 'address': '192.168.56.1', 'count': '4' })` ``` -------------------------------- ### Perform CRUD operations on queues Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/README.md Demonstrates how to get, add, update, and delete queue entries using the API. ```python # Get all queues queues = api.get_resource('/queue/simple').get() # Add a queue api.get_resource('/queue/simple').add( name='office', target='192.168.1.0/24', max_limit='10M/50M' ) # Update a queue api.get_resource('/queue/simple').set(id='*1', disabled='yes') # Delete a queue api.get_resource('/queue/simple').remove(id='*1') ``` -------------------------------- ### Handle RouterOsApiCommunicationError Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/errors.md Example of catching RouterOsApiCommunicationError when an invalid ID is used, printing the formatted and original error messages. ```python from routeros_api.exceptions import RouterOsApiCommunicationError try: queues = api.get_resource('/queue/simple') queues.set(id='*999', name='test') # Invalid id except RouterOsApiCommunicationError as e: print(f"RouterOS error: {e.args[0]}") print(f"Original message: {e.original_message}") ``` -------------------------------- ### Complex Query Example Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/router-os-resource.md Illustrates using `additional_queries` with custom operators like `HasValueQuery` and `IsGreaterQuery` for advanced filtering. ```python from routeros_api import query resource = api.get_resource('/ip/route') # Query with custom operators response = resource.call( 'print', {}, {}, additional_queries=( query.HasValueQuery('static'), query.IsGreaterQuery('distance', '5'), ) ) ``` -------------------------------- ### RouterOsApiPool Constructor Parameters Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/configuration.md Instantiate RouterOsApiPool with connection details and security options. All configuration is done via these constructor arguments. ```python pool = routeros_api.RouterOsApiPool( host: str, username: str = 'admin', password: str = '', port: int = None, plaintext_login: bool = False, use_ssl: bool = False, ssl_verify: bool = True, ssl_verify_hostname: bool = True, ssl_context: ssl.SSLContext = None, ) ``` -------------------------------- ### Asynchronous Call with Promise Handling Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/router-os-resource.md Shows how to initiate an asynchronous call and retrieve results later using `.get()` on the `ResponsePromise`. ```python promise = resource.call_async('print', {}, {}) # Do other work... results = promise.get() ``` -------------------------------- ### Catch All RouterOS API Errors Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/errors.md Example of how to catch any RouterOS API-related errors using the base exception class. ```python import routeros_api from routeros_api.exceptions import RouterOsApiError try: pool = routeros_api.RouterOsApiPool('192.168.1.1') api = pool.get_api() except RouterOsApiError as e: print(f"RouterOS API error: {e}") ``` -------------------------------- ### add Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/router-os-resource.md Adds a new item to the resource. Configuration attributes are passed as keyword arguments. ```APIDOC ## add(**kwargs) ### Description Adds a new item to the resource. ### Method POST ### Endpoint /{resource_path} ### Parameters #### Request Body - **kwargs** (dict) - Required - Configuration attributes for the new item. ### Response #### Success Response (200) - **AsynchronousResponse** - Response containing the ID of the newly created item. ### Request Example ```python queues = api.get_resource('/queue/simple') # Add new queue response = queues.add( name='office', target='192.168.1.0/24', max_limit='512k/2M' ) # Get newly created item id from response new_id = response[0].get('id') if response else None ``` ``` -------------------------------- ### Get DHCP Leases with Count Only Source: https://github.com/socialwifi/routeros-api/blob/master/README.md Retrieve only the count of DHCP leases matching specific criteria. The `count-only` parameter is used for this. ```python >>> api.get_resource('/ip/dhcp-server/lease').call('print', {'count-only': None}).done_message ``` -------------------------------- ### Python Get Resource Method Signature Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/router-os-api.md Defines the signature for the get_resource method, used to access typed API endpoints. ```python def get_resource( self, path: str, structure: dict = None ) -> RouterOsResource ``` -------------------------------- ### Connect with SSL Enabled Source: https://github.com/socialwifi/routeros-api/wiki/How-to-use Establishes an API connection using SSL for secure communication. SSL verification can be customized. ```python connection = routeros_api.RouterOsApiPool('', username='admin', password='', use_ssl=True) ``` ```python connection = routeros_api.RouterOsApiPool('', username='admin', password='', use_ssl=True, ssl_verify=False, ssl_verify_hostname=False) ``` -------------------------------- ### Top-Level and Individual Imports Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/module-reference.md Demonstrates how to import components from the routeros-api library, either all at once or specific classes and functions. ```python # Top-level imports from routeros_api import RouterOsApiPool, connect, query, api_structure # Or individual imports from routeros_api.api import RouterOsApiPool, RouterOsApi, connect from routeros_api.resource import RouterOsResource, RouterOsBinaryResource from routeros_api.exceptions import ( RouterOsApiError, RouterOsApiConnectionError, RouterOsApiCommunicationError, ) from routeros_api.query import ( IsEqualQuery, IsLessQuery, IsGreaterQuery, HasValueQuery, OrQuery, AndQuery, NandQuery, ) from routeros_api.api_structure import ( StringField, BooleanField, IntegerField, TimedeltaField, IpNetworkField, ListField, default_structure, ) ``` -------------------------------- ### Connect using SSL Source: https://github.com/socialwifi/routeros-api/blob/master/README.md Establish a secure connection to a RouterOS device by setting use_ssl to True. This automatically verifies the SSL certificate and hostname. ```python connection = routeros_api.RouterOsApiPool('', username='admin', password='', use_ssl=True) ``` -------------------------------- ### Get DHCP Leases with Count and Filter Source: https://github.com/socialwifi/routeros-api/blob/master/README.md Fetch the count of DHCP leases filtered by a specific server. This combines `count-only` with a `where` clause. ```python >>> api.get_resource('/ip/dhcp-server/lease').call('print', {'count-only': None}, {'server': 'developers'}).done_message ``` -------------------------------- ### Basic Query Usage Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/query.md Demonstrates how to pass custom queries to the call() method for filtering. Use additional_queries to specify comparison operators like IsGreaterQuery and IsLessQuery. ```python from routeros_api import query resource = api.get_resource('/ip/firewall/nat') # Pass custom queries to call() response = resource.call( 'print', {}, {}, additional_queries=( query.IsGreaterQuery('distance', '10'), query.IsLessQuery('rate', '1000'), ) ) ``` -------------------------------- ### Accessing and Iterating Response Items Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/response-format.md Demonstrates how to access individual items, iterate through all items, and get the count of items within an AsynchronousResponse object. ```python response = api.get_resource('/queue/simple').get() # Access first item first_queue = response[0] # Iterate all items for queue in response: print(queue['name']) # Get count count = len(response) ``` -------------------------------- ### Connect to Lab Environment with Self-Signed Cert Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/configuration.md Use this configuration for lab environments where SSL is enabled but certificates are self-signed and do not need verification. ```python pool = routeros_api.RouterOsApiPool( '192.168.88.1', username='admin', password='admin', plaintext_login=True, use_ssl=True, ssl_verify=False, ssl_verify_hostname=False ) api = pool.get_api() ``` -------------------------------- ### Fetch a File from a URL Source: https://github.com/socialwifi/routeros-api/blob/master/README.md This snippet demonstrates how to fetch a file from a given URL and save it to a destination path on the RouterOS device. ```python >>> api.get_resource('/tool').call('fetch', {'url': 'http://example.com', 'dst-path': 'output.html'}) ``` -------------------------------- ### Handling RouterOS API Errors Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/response-format.md Provides an example of how to catch RouterOsApiCommunicationError and access the original error message from RouterOS using the 'error' property. ```python try: response = api.get_resource('/queue/simple').set(id='*999') except RouterOsApiCommunicationError as e: print(f"Error: {e.original_message.decode()}") ``` -------------------------------- ### Add Rules Source: https://github.com/socialwifi/routeros-api/wiki/How-to-use Explains how to add new entries to a resource list, including how to handle attributes with hyphens. ```APIDOC ## Add rules `list.add(attribute="vale", attribute_n="value")` **NOTE**: Atributes with "-", like max-limit use underscore "_" max_limit ### Example: `list_queues.add(name="001", max_limit="512k/4M", target="192.168.10.1/32")` ``` -------------------------------- ### Handle RouterOsApiParsingError Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/errors.md Example of catching a RouterOsApiParsingError when the API response format is invalid. This typically points to a RouterOS protocol bug or data corruption. ```python # Triggered if RouterOS sends malformed response # (This indicates a protocol bug in RouterOS or data corruption) try: api.get_resource('/').get() except RouterOsApiParsingError as e: print(f"Cannot parse RouterOS response: {e}") ``` -------------------------------- ### Conditional Async Execution with Promises Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/async-support.md Demonstrates how to initiate an asynchronous API call and retrieve the result only when it's ready. Useful for non-blocking operations where you might perform other tasks while waiting. ```python import routeros_api pool = routeros_api.RouterOsApiPool('192.168.1.1') api = pool.get_api() resource = api.get_resource('/queue/simple') # Async execution promise = resource.call_async('print', {}, {'disabled': 'no'}) # Check if more data needed print("Response in progress...") # Blocking wait when ready queues = promise.get() print(f"Found {len(queues)} enabled queues") ``` -------------------------------- ### Handle FatalRouterOsApiError Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/errors.md Example of catching a FatalRouterOsApiError during an API call. This error indicates a protocol desynchronization or malformed data that leads to connection closure. ```python # Triggered during protocol parsing if malformed data received try: api = pool.get_api() api.get_resource('/queue/simple').get() except FatalRouterOsApiError as e: print(f"Fatal protocol error: {e}") # Connection is now closed ``` -------------------------------- ### Connect with Custom Port Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/configuration.md Configure the API client to connect to a RouterOS device on a non-standard port. This example uses SSL and plaintext login. ```python pool = routeros_api.RouterOsApiPool( 'router.local', username='admin', password='admin', port=9000, plaintext_login=True, use_ssl=True ) api = pool.get_api() ``` -------------------------------- ### Custom SSL Context Configuration Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/configuration.md Establishes a connection with a custom SSL context for advanced control over SSL parameters, including loading custom CA certificates and setting verification modes. ```python import ssl import routeros_api # Create custom context ssl_context = ssl.create_default_context() # Load custom CA certificate ssl_context.load_verify_locations('/path/to/ca-bundle.crt') # Set custom verify mode ssl_context.check_hostname = True ssl_context.verify_mode = ssl.CERT_REQUIRED # Use context pool = routeros_api.RouterOsApiPool( '192.168.1.1', username='admin', password='admin', ssl_context=ssl_context ) api = pool.get_api() ``` -------------------------------- ### Python Get Binary Resource Method Signature Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/router-os-api.md Defines the signature for the get_binary_resource method, which retrieves untyped resource objects for raw bytes communication. ```python def get_binary_resource(self, path: str) -> RouterOsBinaryResource ``` -------------------------------- ### Print (List) Response Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/api-reference/response-format.md Demonstrates the typical response structure for a 'print' command that lists resources. It returns a list of dictionaries, where each dictionary represents a resource with its properties. ```APIDOC ## Print (List) Response ### Description This endpoint retrieves a list of resources. The response is a JSON array where each element is an object representing a resource with its attributes. ### Method GET (or equivalent SDK call) ### Endpoint `/queue/simple` ### Response #### Success Response (200) - **id** (string) - Unique identifier for the resource. - **name** (string) - The name of the resource. - **target** (string) - The target network or IP address. #### Response Example ```json [ {'id': '*1', 'name': 'queue1', 'target': '192.168.1.0/24'}, {'id': '*2', 'name': 'queue2', 'target': '192.168.2.0/24'} ] ``` ``` -------------------------------- ### Python HasValueQuery Example Source: https://github.com/socialwifi/routeros-api/blob/master/_autodocs/query.md Use HasValueQuery to find items where a specific attribute has a non-empty value. This is useful for filtering based on the presence of data in an attribute. ```python from routeros_api import query # Find addresses with non-empty comment addresses = api.get_resource('/ip/firewall/address-list') response = addresses.call( 'print', {}, {}, additional_queries=(query.HasValueQuery('comment'),) ) # Find routes with non-empty gateway routes = api.get_resource('/ip/route') response = routes.call( 'print', {}, {}, additional_queries=(query.HasValueQuery('gateway'),) ) ```