mardi 15 décembre 2020

Python check ipaddress against a subnet to create a route

apologies for this newbie question, but i try to learn ;)

iam currently working on a script that should create a route and check if the user inputs make sense. It should check if the entered network id and mask is valid and then it should also check if the nexthop gw is within that network.

but iam facing two issues:

  1. i cannot break out of the while loop when i type "no" while the script runs. It works only when i change it to "while choice == "yes" without or "y" statement
  2. i do not understand why this check does not work: if ipaddress.ip_address(gateway) in network == True, the script always goes through to else.

at the end iam happy when i have the dictionary filled with subnet, ip address, gateway and route tag.

i added some sample output below.

Version: Python3.9.1

import ipaddress

networks = {}

def network_input():
    choice = input('Propagate a new network, yes/no? ')
    while choice == 'yes' or 'y':
        network = input('Network-ID with CIDR notation (x.x.x.x/x): ')
        try:
            network = ipaddress.ip_network(network)
        except ValueError:
            print('invalid Address or Netmask:', network)
            return network_input()
        else:
            networks.update({str(network.network_address):(str(network.netmask))})
            print(networks)
            gateway = input("Next Hop Gateway: ")
            try:
                gateway = ipaddress.ip_address(gateway)
            except ValueError:
                print('invalid Gateway:', gateway)
                return network_input()
            else:
                if ipaddress.ip_address(gateway) in network == True:
                    tag = input("Route Description: ")
                    networks.update({str(network.network_address):(str(network.netmask),str(gateway),tag)})
                    print(networks)
                    return network_input()
                else:
                    print('Gateway is not part of the subnet', network)
                    return network_input()

network_input()

Output:

Propagate a new network, yes/no? yes
Network-ID with CIDR notation (x.x.x.x/x): 192.168.2.0/24
{'192.168.2.0': '255.255.255.0'}
Next Hop Gateway: 192.168.2.1
Gateway is not part of the subnet 192.168.2.0/24
Propagate a new network, yes/no?

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire