如何使用 Python RouterOS-api 添加 DHCP 客户端
使用以下 Python 代码通过 Python RouterOS-api 包在 bridge 接口上添加新的 DHCP 客户端:
add_dhcp_client.py
# Add a new DHCP client on bridge interface
print(f"Adding new DHCP client on bridge interface")
dhcp_client_resource = api.get_resource('/ip/dhcp-client')
try:
dhcp_client_resource.add(interface='bridge', disabled='no')
except routeros_api.exceptions.RouterOsApiCommunicationError as e:
error_message = str(e)
if 'dhcp-client on that interface already exists' in error_message:
print("DHCP client already exists")
else:
raise e为方便起见,以下是此代码作为函数:
add_dhcp_client_function.py
def add_dhcp_client(api, interface):
"""
Add a new DHCP client on bridge interface.
Parameters:
- api (routeros_api.RouterOsApi): The RouterOS API object.
- interface (str): The name of the bridge interface.
Returns:
- bool: True if the DHCP client was added successfully, False otherwise (if it already exists).
Raises:
- routeros_api.exceptions.RouterOsApiCommunicationError:
If there is an error in the RouterOS API communication, except if the error is just
that the DHCP client already exists (in that case, it returns False).
"""
# Add a new DHCP client on bridge interface
dhcp_client_resource = api.get_resource('/ip/dhcp-client')
try:
dhcp_client_resource.add(interface='bridge', disabled='no')
return True
except routeros_api.exceptions.RouterOsApiCommunicationError as e:
error_message = str(e)
if 'dhcp-client on that interface already exists' in error_message:
print("DHCP client already exists")
else:
raise e
return False
# Example usage
add_dhcp_client(api, 'bridge')完整示例
以下示例适用于工厂配置的 MikroTik wAP-LTE 套件。
add_dhcp_client_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()
# Add a new DHCP client on bridge interface
print(f"Adding new DHCP client on bridge interface")
dhcp_client_resource = api.get_resource('/ip/dhcp-client')
try:
dhcp_client_resource.add(interface='bridge', disabled='no')
except routeros_api.exceptions.RouterOsApiCommunicationError as e:
error_message = str(e)
if 'dhcp-client on that interface already exists' in error_message:
print("DHCP client already exists")
else:
raise eCheck out similar posts by category:
MikroTik, Networking
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow