import asyncio import yaml from asusrouter import AsusRouter, AsusData from asusrouter.modules.port_forwarding import PortForwardingRule with open("credentials.yml") as stream: try: credentials = yaml.safe_load(stream)['credentials'] except yaml.YAMLError as exc: print(exc) router = AsusRouter( hostname=credentials.get('ip'), username=credentials.get('user'), password=credentials.get('password'), use_ssl=credentials.get('use_ssl', False) ) existing_rules = [] new_rules = [] async def main(rule_tag, new_ip): global existing_rules global new_rules await router.async_connect() # Get port forwarding rules pfwd = await router.async_get_data(AsusData.PORT_FORWARDING) # Store existing rules that match tag for rule in pfwd['rules']: if rule_tag in rule.name: existing_rules += [ PortForwardingRule( name=rule.name, ip_address=rule.ip_address, port=rule.port, protocol=rule.protocol, ip_external=rule.ip_external, port_external=rule.port_external ) ] new_rules += [ PortForwardingRule( name=rule.name, ip_address=rule.ip_address, port=rule.port, protocol=rule.protocol, ip_external=new_ip, port_external=rule.port_external ) ] result = await router.async_set_port_forwarding_rules(new_rules) if result: print("New records set.") await router.async_disconnect() if __name__ == "__main__": asyncio.run(main("TEST", "192.168.1.2"))