如何使用 Python 和 routeros_api 向 MikroTik 路由器添加 IP 地址

这实现了使用 routeros_api Python 库向 MikroTik 路由器添加 IP 地址的不存在则添加功能。

add_ip_address.py
def add_ip_address(api, network):
    """
    Add an IP address to the bridge interface.

    :param api: The RouterOS API object.
    :param network: The network address to add (e.g., '10.1.2.3/24').
    """
    # Add an IP address to the bridge interface
    print(f"Adding IP address {network} to bridge interface")
    try:
        api.get_resource('/ip/address').add(address=network, interface='bridge')
    except routeros_api.exceptions.RouterOsApiCommunicationError as e:
        if "already have such address" in str(e):
            print("IP address already exists")
        else:
            raise e

Check out similar posts by category: RouterOS, MikroTik, Python