如何使用 Python RouterOS-api 向接口添加 IP 地址

使用以下 Python 代码通过 Python RouterOS-api 包向接口添加 IP 地址:

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")

完整示例

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