Como adicionar endereço IP à interface usando Python RouterOS-api

Use o seguinte código Python para adicionar um endereço IP a uma interface usando o pacote Python RouterOS-api:

add_ip_address.py

def add_ip_address(api, ip, interface):
    """
    Adds an IP address to a specified interface using the RouterOS API.

    Parameters:
    - api (routeros_api.RouterOsApi): The RouterOS API instance.
    - ip (str): The IP address to be added.
    - interface (str): The interface to which the IP address will be added.

    Returns:
    - bool: True if the IP address was added successfully, False if the IP address already exists on the interface.

    Raises:
    - routeros_api.exceptions.RouterOsApiCommunicationError: If there is an error communicating with the RouterOS API.
    """
    try:
        ip_resource = api.get_resource('/ip/address')
        ip_resource.add(interface=interface, address=ip)
        return True
    except routeros_api.exceptions.RouterOsApiCommunicationError as e:
        error_message = str(e)
        if 'already have such address' in error_message:
            return False
        else:
            raise e

# Example usage
add_ip_address(api, ip="10.1.2.3/24", interface="bridge")

Exemplo completo

add_ip_address_full.py
#!/usr/bin/env python3
import routeros_api

connection = routeros_api.RouterOsApiPool(
    '192.168.88.1', username='admin', password='L9TYAUV7R8',
    plaintext_login=True
)
api = connection.get_api()


def add_ip_address(api, ip, interface):
    """
    Adds an IP address to a specified interface using the RouterOS API.

    Parameters:
    - api (routeros_api.RouterOsApi): The RouterOS API instance.
    - ip (str): The IP address to be added.
    - interface (str): The interface to which the IP address will be added.

    Returns:
    - bool: True if the IP address was added successfully, False if the IP address already exists on the interface.

    Raises:
    - routeros_api.exceptions.RouterOsApiCommunicationError: If there is an error communicating with the RouterOS API.
    """
    try:
        ip_resource = api.get_resource('/ip/address')
        ip_resource.add(interface=interface, address=ip)
        return True
    except routeros_api.exceptions.RouterOsApiCommunicationError as e:
        error_message = str(e)
        if 'already have such address' in error_message:
            return False
        else:
            raise e

# Example usage
add_ip_address(api, ip="10.1.2.3/24", interface="bridge")

Check out similar posts by category: MikroTik Networking