### Install AsusRouter Python Package Source: https://context7.com/vaskivskyi/asusrouter/llms.txt Installs the AsusRouter library using pip. This is the primary method for adding the library to your Python environment. ```bash pip install asusrouter ``` -------------------------------- ### Control OpenVPN Client/Server with Python Source: https://context7.com/vaskivskyi/asusrouter/llms.txt This Python script demonstrates how to start, stop, and check the status of OpenVPN client and server instances on an Asus router. It requires the 'asusrouter' and 'aiohttp' libraries. The script connects to the router, controls OpenVPN services, retrieves OpenVPN data, and then disconnects. ```python import aiohttp import asyncio from asusrouter import AsusRouter, AsusData from asusrouter.modules.openvpn import AsusOVPNClient, AsusOVPNServer async def control_openvpn(): session = aiohttp.ClientSession() router = AsusRouter( hostname="192.168.1.1", username="admin", password="password", session=session, ) await router.async_connect() identity = await router.async_get_identity() # Start OpenVPN client 1 result = await router.async_set_state( AsusOVPNClient.ON, id=1, identity=identity ) print(f"VPN Client 1 started: {result}") # Stop OpenVPN client 1 result = await router.async_set_state( AsusOVPNClient.OFF, id=1, identity=identity ) print(f"VPN Client 1 stopped: {result}") # Start OpenVPN server 1 result = await router.async_set_state( AsusOVPNServer.ON, id=1, identity=identity ) print(f"VPN Server 1 started: {result}") # Get OpenVPN status ovpn_data = await router.async_get_data(AsusData.OPENVPN) print(f"OpenVPN status: {ovpn_data}") await router.async_disconnect() await session.close() asyncio.run(control_openvpn()) ``` -------------------------------- ### Initialize and Connect to AsusRouter Source: https://github.com/vaskivskyi/asusrouter/blob/dev/README.md Demonstrates how to initialize the AsusRouter client, establish an asynchronous connection, retrieve network data, and perform a clean disconnection. ```python import aiohttp import asyncio from asusrouter import AsusRouter, AsusData loop = asyncio.new_event_loop() session = aiohttp.ClientSession(loop=loop) router = AsusRouter( hostname="router.my.address", username="admin", password="password", use_ssl=True, session=session, ) loop.run_until_complete(router.async_connect()) data = loop.run_until_complete(router.async_get_data(AsusData.NETWORK)) print(data) loop.run_until_complete(router.async_disconnect()) loop.run_until_complete(session.close()) ``` -------------------------------- ### Initialize AsusRouter Class and Connect Source: https://context7.com/vaskivskyi/asusrouter/llms.txt Demonstrates how to initialize the AsusRouter class and establish an asynchronous connection to an ASUS router. It covers essential parameters like hostname, username, password, and optional settings such as port, SSL usage, and session management. ```python import aiohttp import asyncio from asusrouter import AsusRouter, AsusData async def main(): # Create aiohttp session session = aiohttp.ClientSession() # Initialize router interface with full configuration router = AsusRouter( hostname="192.168.1.1", # Router IP or hostname (required) username="admin", # Router username (required) password="your_password", # Router password (required) port=8443, # Custom port (optional, auto-detected) use_ssl=True, # Enable HTTPS (optional, default: False) cache_time=5.0, # Cache duration in seconds (optional) session=session, # Reuse existing aiohttp session (optional) ) # Connect to the router connected = await router.async_connect() print(f"Connected: {connected}") # Check connection status print(f"Connection status: {router.connected}") print(f"Web panel URL: {router.webpanel}") # Disconnect when done await router.async_disconnect() await session.close() asyncio.run(main()) ``` -------------------------------- ### Manage Port Forwarding Rules with Python Source: https://context7.com/vaskivskyi/asusrouter/llms.txt Demonstrates how to enable port forwarding, fetch existing rules, add new rules, and remove specific rules using the asusrouter library. It requires an active session and router authentication credentials. ```python import aiohttp import asyncio from asusrouter import AsusRouter, AsusData from asusrouter.modules.port_forwarding import PortForwardingRule, AsusPortForwarding async def manage_port_forwarding(): session = aiohttp.ClientSession() router = AsusRouter( hostname="192.168.1.1", username="admin", password="password", session=session, ) await router.async_connect() # Enable port forwarding globally result = await router.async_set_state(AsusPortForwarding.ON) print(f"Port forwarding enabled: {result}") # Get current port forwarding rules pf_data = await router.async_get_data(AsusData.PORT_FORWARDING) current_rules = pf_data.get("rules", []) print(f"Current rules: {len(current_rules)}") # Create new port forwarding rules web_server_rule = PortForwardingRule( name="Web Server", ip_address="192.168.1.100", port="80", port_external="8080", protocol="TCP", ip_external="" ) ssh_rule = PortForwardingRule( name="SSH Access", ip_address="192.168.1.100", port="22", port_external="2222", protocol="TCP", ip_external="" ) # Add new rules result = await router.async_set_port_forwarding_rules([web_server_rule, ssh_rule]) print(f"Rules added: {result}") # Remove rules by IP address remaining_rules = await router.async_remove_port_forwarding_rules( ips=["192.168.1.100"] ) print(f"Remaining rules after removal: {len(remaining_rules)}") # Remove specific rule remaining_rules = await router.async_remove_port_forwarding_rules( rules=[web_server_rule] ) print(f"After specific removal: {len(remaining_rules)}") # Apply a complete set of rules (replaces all existing) new_rules = [ PortForwardingRule( name="Game Server", ip_address="192.168.1.50", port="27015", port_external="27015", protocol="BOTH", ip_external="" ) ] result = await router.async_apply_port_forwarding_rules(new_rules) print(f"Rules applied: {result}") await router.async_disconnect() await session.close() asyncio.run(manage_port_forwarding()) ``` -------------------------------- ### Fetch Router Data Asynchronously Source: https://context7.com/vaskivskyi/asusrouter/llms.txt Shows how to fetch various types of data from an ASUS router using the `async_get_data` method and `AsusData` enum. This includes CPU usage, RAM, network traffic, client information, firmware status, WAN details, and temperature. It also demonstrates how to force fresh data retrieval, bypassing the cache. ```python import aiohttp import asyncio from asusrouter import AsusRouter, AsusData async def get_router_data(): session = aiohttp.ClientSession() router = AsusRouter( hostname="192.168.1.1", username="admin", password="password", session=session, ) await router.async_connect() # Get CPU usage statistics cpu_data = await router.async_get_data(AsusData.CPU) print(f"CPU Data: {cpu_data}") # Output: {'cpu1_total': 15.2, 'cpu1_usage': 3.1, 'cpu2_total': 15.2, ...} # Get RAM usage ram_data = await router.async_get_data(AsusData.RAM) print(f"RAM Data: {ram_data}") # Output: {'total': 524288, 'free': 234567, 'used': 289721, 'usage': 55.2} # Get network traffic statistics network_data = await router.async_get_data(AsusData.NETWORK) print(f"Network: {network_data}") # Force fresh data (bypass cache) fresh_cpu = await router.async_get_data(AsusData.CPU, force=True) # Get connected clients clients = await router.async_get_data(AsusData.CLIENTS) for mac, client in clients.items(): print(f"Client: {client.description.name} - {client.connection.ip_address}") # Get firmware information firmware = await router.async_get_data(AsusData.FIRMWARE) print(f"Firmware update available: {firmware.get('state', False)}") # Get WAN status wan_data = await router.async_get_data(AsusData.WAN) print(f"WAN IP: {wan_data.get('ip_address')}") # Get temperature readings temp_data = await router.async_get_data(AsusData.TEMPERATURE) print(f"CPU Temp: {temp_data.get('cpu')}°C") await router.async_disconnect() await session.close() asyncio.run(get_router_data()) ``` -------------------------------- ### Perform System Operations with Python Source: https://context7.com/vaskivskyi/asusrouter/llms.txt This Python script demonstrates various system-level operations on an Asus router, such as checking for firmware updates, restarting network services, and rebooting specific nodes or the entire router. It utilizes the 'asusrouter' and 'aiohttp' libraries. Ensure you have the necessary permissions and understand the implications before executing commands like router reboots. ```python import aiohttp import asyncio from asusrouter import AsusRouter from asusrouter.modules.system import AsusSystem async def system_operations(): session = aiohttp.ClientSession() router = AsusRouter( hostname="192.168.1.1", username="admin", password="password", session=session, ) await router.async_connect() # Check for firmware updates result = await router.async_set_state(AsusSystem.FIRMWARE_CHECK) print(f"Firmware check triggered: {result}") # Restart wireless interfaces result = await router.async_set_state(AsusSystem.RESTART_WIRELESS) print(f"Wireless restarted: {result}") # Restart firewall result = await router.async_set_state(AsusSystem.RESTART_FIREWALL) print(f"Firewall restarted: {result}") # Restart DNS service result = await router.async_set_state(AsusSystem.RESTART_DNSMASQ) print(f"DNS restarted: {result}") # Restart QoS result = await router.async_set_state(AsusSystem.RESTART_QOS) print(f"QoS restarted: {result}") # Reboot a specific AiMesh node (requires MAC address) result = await router.async_set_state( AsusSystem.NODE_REBOOT, device_list="AA:BB:CC:DD:EE:FF" ) print(f"Node rebooted: {result}") # Rebuild AiMesh network result = await router.async_set_state(AsusSystem.AIMESH_REBUILD) print(f"AiMesh rebuild triggered: {result}") # Reboot the router (use with caution!) # result = await router.async_set_state(AsusSystem.REBOOT) # print(f"Router rebooting: {result}") await router.async_disconnect() await session.close() asyncio.run(system_operations()) ``` -------------------------------- ### Handle AsusRouter Communication Exceptions Source: https://context7.com/vaskivskyi/asusrouter/llms.txt Demonstrates how to implement robust error handling for asynchronous router operations using specific exception classes provided by the library. It covers common failure scenarios like connection timeouts, authentication issues, and data errors. ```python import aiohttp import asyncio from asusrouter import AsusRouter, AsusData from asusrouter.error import ( AsusRouterError, AsusRouterConnectionError, AsusRouterAccessError, AsusRouterTimeoutError, AsusRouter404Error, AsusRouterDataError, AsusRouterIdentityError, AsusRouterSSLCertificateError ) async def handle_errors(): session = aiohttp.ClientSession() router = AsusRouter( hostname="192.168.1.1", username="admin", password="password", session=session, use_ssl=True ) try: await router.async_connect() data = await router.async_get_data(AsusData.CLIENTS) print(f"Clients: {data}") except AsusRouterConnectionError as e: print(f"Connection failed: {e}") except AsusRouterAccessError as e: print(f"Access denied: {e}") except AsusRouterTimeoutError as e: print(f"Request timed out: {e}") except AsusRouter404Error as e: print(f"Endpoint not found: {e}") except AsusRouterDataError as e: print(f"Data error: {e}") except AsusRouterIdentityError as e: print(f"Identity error: {e}") except AsusRouterSSLCertificateError as e: print(f"SSL error: {e}") except AsusRouterError as e: print(f"General error: {e}") finally: await router.async_disconnect() await session.close() asyncio.run(handle_errors()) ``` -------------------------------- ### Retrieve Device Identity with AsusRouter Source: https://context7.com/vaskivskyi/asusrouter/llms.txt Demonstrates how to connect to an ASUS router and retrieve detailed device information including model, firmware, and supported features. It shows both cached and forced-refresh methods for identity data. ```python import aiohttp import asyncio from asusrouter import AsusRouter async def get_device_info(): session = aiohttp.ClientSession() router = AsusRouter( hostname="192.168.1.1", username="admin", password="password", session=session, ) await router.async_connect() # Get device identity (cached after first connection) identity = await router.async_get_identity() print(f"Brand: {identity.brand}") print(f"Model: {identity.model}") print(f"Serial: {identity.serial}") print(f"MAC Address: {identity.mac}") print(f"Firmware: {identity.firmware}") print(f"Is Merlin: {identity.merlin}") print(f"AiMesh Support: {identity.aimesh}") print(f"WLAN Interfaces: {identity.wlan}") print(f"Aura RGB Support: {identity.aura}") print(f"LED Control: {identity.led}") print(f"Available Services: {identity.services}") # Force refresh identity fresh_identity = await router.async_get_identity(force=True) await router.async_disconnect() await session.close() asyncio.run(get_device_info()) ``` -------------------------------- ### Control Aura RGB Lighting with Python Source: https://context7.com/vaskivskyi/asusrouter/llms.txt This snippet demonstrates how to configure Aura RGB lighting effects, including static colors, breathing, gradients, and rainbow modes. It requires an active AsusRouter session and utilizes the AsusAura and ColorRGB modules. ```python import aiohttp import asyncio from asusrouter import AsusRouter from asusrouter.modules.aura import AsusAura from asusrouter.modules.color import ColorRGB async def control_aura(): session = aiohttp.ClientSession() router = AsusRouter( hostname="192.168.1.1", username="admin", password="password", session=session, ) await router.async_connect() # Turn off Aura RGB result = await router.async_set_state(AsusAura.OFF) print(f"Aura off: {result}") # Set static color mode with custom color result = await router.async_set_state( AsusAura.STATIC, color=ColorRGB((255, 0, 0)), # Red color brightness=80 ) print(f"Static red set: {result}") # Set breathing effect result = await router.async_set_state(AsusAura.BREATHING) print(f"Breathing effect: {result}") # Set gradient effect with multiple colors result = await router.async_set_state( AsusAura.GRADIENT, color=[ ColorRGB((255, 0, 0)), # Red ColorRGB((0, 255, 0)), # Green ColorRGB((0, 0, 255)) # Blue ] ) print(f"Gradient set: {result}") # Rainbow effect (no color selection needed) result = await router.async_set_state(AsusAura.RAINBOW) print(f"Rainbow effect: {result}") # Set color for specific zone only result = await router.async_set_state( AsusAura.STATIC, color=ColorRGB((0, 255, 255)), # Cyan zone=0, # First zone brightness=100 ) print(f"Zone 0 cyan: {result}") await router.async_disconnect() await session.close() asyncio.run(control_aura()) ``` -------------------------------- ### Manage WLAN Radio States Source: https://context7.com/vaskivskyi/asusrouter/llms.txt Provides instructions for enabling or disabling specific wireless radios and guest networks. It demonstrates how to target specific bands using api_id parameters. ```python import aiohttp import asyncio from asusrouter import AsusRouter from asusrouter.modules.wlan import AsusWLAN async def control_wlan(): session = aiohttp.ClientSession() router = AsusRouter( hostname="192.168.1.1", username="admin", password="password", session=session, ) await router.async_connect() # Turn off 2.4GHz radio (api_id=0) result = await router.async_set_state( AsusWLAN.OFF, api_type="wlan", api_id=0 # 0=2.4GHz, 1=5GHz, 2=5GHz-2, 3=6GHz ) print(f"2.4GHz disabled: {result}") # Turn on 5GHz radio (api_id=1) result = await router.async_set_state( AsusWLAN.ON, api_type="wlan", api_id=1 ) print(f"5GHz enabled: {result}") # Control guest network (api_id format: "unit.guest_index") result = await router.async_set_state( AsusWLAN.OFF, api_type="gwlan", api_id="0.1" # First guest network on 2.4GHz ) print(f"Guest network disabled: {result}") await router.async_disconnect() await session.close() asyncio.run(control_wlan()) ``` -------------------------------- ### Capture Router API Dumps for Debugging Source: https://context7.com/vaskivskyi/asusrouter/llms.txt Utilizes the AsusRouterDump utility to capture raw API responses during router operations. This is useful for debugging and testing by saving data to a local folder as an archive. ```python import aiohttp import asyncio from asusrouter import AsusRouter, AsusData from asusrouter.tools.dump import AsusRouterDump async def dump_router_data(): session = aiohttp.ClientSession() # Create dump context manager with AsusRouterDump( output_folder="./router_dumps", full_dump=True, # Include raw response content archive=True # Save as ZIP file ) as dumper: router = AsusRouter( hostname="192.168.1.1", username="admin", password="password", session=session, dumpback=dumper.dump # Attach dump callback ) await router.async_connect() # All API calls will be logged to the dump await router.async_get_data(AsusData.CLIENTS) await router.async_get_data(AsusData.NETWORK) await router.async_get_data(AsusData.CPU) await router.async_get_data(AsusData.RAM) await router.async_disconnect() # Dump files are saved when context manager exits print("Dump saved to ./router_dumps/") await session.close() asyncio.run(dump_router_data()) ``` -------------------------------- ### Control Router LED State Source: https://context7.com/vaskivskyi/asusrouter/llms.txt Shows how to toggle the router's LED indicators on or off using the AsusLED module. This requires an active connection to the router instance. ```python import aiohttp import asyncio from asusrouter import AsusRouter from asusrouter.modules.led import AsusLED async def control_led(): session = aiohttp.ClientSession() router = AsusRouter( hostname="192.168.1.1", username="admin", password="password", session=session, ) await router.async_connect() # Turn LED off result = await router.async_set_state(AsusLED.OFF) print(f"LED turned off: {result}") # Turn LED on result = await router.async_set_state(AsusLED.ON) print(f"LED turned on: {result}") await router.async_disconnect() await session.close() asyncio.run(control_led()) ``` -------------------------------- ### Manage Parental Controls with Python Source: https://context7.com/vaskivskyi/asusrouter/llms.txt This snippet shows how to enable or disable parental controls, block internet access for specific devices, and define time-based scheduling rules. It uses the ParentalControlRule class to define access policies. ```python import aiohttp import asyncio from asusrouter import AsusRouter, AsusData from asusrouter.modules.parental_control import ( AsusParentalControl, AsusBlockAll, ParentalControlRule, PCRuleType ) async def manage_parental_controls(): session = aiohttp.ClientSession() router = AsusRouter( hostname="192.168.1.1", username="admin", password="password", session=session, ) await router.async_connect() # Enable parental control globally result = await router.async_set_state(AsusParentalControl.ON) print(f"Parental control enabled: {result}") # Disable parental control result = await router.async_set_state(AsusParentalControl.OFF) print(f"Parental control disabled: {result}") # Enable "Block All" mode (blocks all internet access) result = await router.async_set_state(AsusBlockAll.ON) print(f"Block all enabled: {result}") # Add a time-based rule for a specific device rule = ParentalControlRule( mac="AA:BB:CC:DD:EE:FF", name="Kid's Tablet", type=PCRuleType.TIME, timemap="W03E21000700