routeros-api

repository·master·Indexed 43 days ago

https://github.com/socialwifi/routeros-api

A Python API client for MikroTik RouterBoard devices that provides a structured way to interact with RouterOS. It supports CRUD operations on resources, SSL connections, and specific requirements for RouterOS v6.43+ via the plaintext_login parameter.

Tokens
1.8K
Snippets
7
Records
8
Agent score
6%

What's inside routeros-api

  1. Use SSL for connections

    master

    To enable SSL, set use_ssl=True. By default, this will verify the certificate and hostname. If you are using self-signed certificates and need to bypass verification, set ssl_verify=False and ssl_verify_hostname=False.

    # Standard SSL connection
    connection = routeros_api.RouterOsApiPool('<IP>', username='admin', password='', use_ssl=True)
    
    # SSL connection with verification disabled (e.g., for self-signed certs)
    connection = routeros_api.RouterOsApiPool(
        '<IP>',
        username='admin',
        password='',
        use_ssl=True,
        ssl_verify=False,
        ssl_verify_hostname=False,
    )
  2. Connect to a MikroTik RouterOS device

    master

    Use routeros_api.RouterOsApiPool to establish a connection. You must then call .get_api() to obtain the API instance used for executing commands.

    Important for RouterOS v6.43+: These versions require the plaintext_login=True parameter. It is highly recommended to use this option only when use_ssl=True is also enabled for security.

    import routeros_api
    
    connection = routeros_api.RouterOsApiPool('IP', username='admin', password='', plaintext_login=True)
    api = connection.get_api()
  3. Handle non-UTF-8 characters in API responses

    master

    The API does not assume a specific encoding. If you encounter non-UTF-8 characters, you can specify a custom encoding (like latin-1 or windows-1250) by providing a custom defaultdict using StringField as the structure for the resource.

    import collections
    import routeros_api
    from routeros_api.api_structure import StringField
    
    connection = routeros_api.RouterOsApiPool('ip', username='admin', password='password', plaintext_login=True)
    api = connection.get_api()
    
    # Define a structure that uses a specific encoding
    default_structure = collections.defaultdict(lambda: StringField(encoding='windows-1250'))
    api.get_resource('/system/identity', structure=default_structure).get()
  4. Manage RouterOS resources (Add, Set, Get, Remove)

    master

    Once you have a resource via api.get_resource('/path'), you can perform CRUD operations:

    • Fetch all/list: resource.get()
    • Add a rule: resource.add(attr='val'). Note: Attributes with hyphens in CLI (e.g., max-limit) must use underscores in Python (max_limit).
    • Update a value: resource.set(id='*1', attr='new_val') or use .call('set', ...).
    • Get a specific element: resource.get(attr='val').
    • Remove an element: resource.remove(id='*1').
    list_queues = api.get_resource('/queue/simple')
    
    # Add
    list_queues.add(name='001', max_limit='512k/4M', target='192.168.10.1/32')
    
    # Update
    list_queues.set(id='*2', name='john')
    
    # Get
    item = list_queues.get(name='john')
    
    # Remove
    list_queues.remove(id='*2')
  5. Get result counts using 'count-only'

    master

    To mimic the RouterOS CLI count-only behavior, use the .call('print', ...) method on a resource. This is useful for checking the number of items matching a specific criteria without downloading the full list.

    # Count all DHCP leases
    count_res = api.get_resource('/ip/dhcp-server/lease').call('print', {'count-only': None})
    print(count_res.done_message['ret'])
    
    # Count DHCP leases where server is 'developers'
    count_res = api.get_resource('/ip/dhcp-server/lease').call('print', {'count-only': None}, {'server': 'developers'})
    print(count_res.done_message['ret'])
  6. Execute arbitrary commands via the API

    master

    Use api.get_resource('/').call('<resource>', { <params> }) to execute specific RouterOS commands.

    For binary data, use api.get_binary_resource('/').call('<resource>', { <params> }). In this mode, all dictionary values must be encoded as bytes, and the returned results will also be bytes.

    # Example: Fetching a URL
    api.get_resource('/').call('fetch', {'url': 'http://example.com', 'dst-path': 'output.html'})
    
    # Example: Pinging an address
    api.get_resource('/').call('ping', {'address': '8.8.8.8', 'count': '4'})
  7. Run scripts and monitor processes

    master

    You can run scripts and retrieve their output, or use the monitor command to track real-time status.

    Running a script: Use .call('run', {'number': '0'}). The result is available in response.done_message['ret'].

    # Run a script
    response = api.get_resource('/system/script').call('run', {'number': '0'})
    print(response.done_message['ret'])
    
    # Monitor PoE status
    poe_status = api.get_resource('/interface/ether/poe').call('monitor', {'numbers': '0', 'once': None})
  8. Configure RouterOsApiPool connection parameters

    master

    The RouterOsApiPool constructor accepts the following parameters:

    ParameterTypeDefaultDescription
    hostStringRequiredHostname or IP of device
    usernameString'admin'Login username
    passwordString''Login password
    portInteger8728TCP Port for API (8729 if using SSL)
    plaintext_loginBooleanFalseTry plaintext login (required for RouterOS 6.43+)
    use_sslBooleanFalseUse SSL
    ssl_verifyBooleanTrueVerify the SSL certificate
    ssl_verify_hostnameBooleanTrueVerify the SSL certificate hostname matches
    ssl_contextObjectNoneCustom SSL context object (overrides other SSL options)