Use case
I am trying to write a script for doing security group based on user’s input. the IpRanges is a list of dictionary. I intend to do a method which generate multiple dictionaries with the same key but different values, and put these dictionaries into a list.
ipaddress.ip_network method can evaluate both host ip address and ip subnet, if the value is not a valid subnet or ipv4 address an exception will be thrown, the collection will be based on only valid subnet or host ip address.
from ipaddress import ip_network results = [] process_results = [] stop = int(input("how many source ip address you want")) print("Press enter with empty response to quit.") for i in range(0,stop): ip = input("Source address:") if ip is not "": try: ip_network(ip) results.append(ip) except ValueError as e: print(e) else: break # collecting the dictionary / dictionaries in a list for result in results: results_dict = {'ip': result} process_results.append(results_dict) print(process_results)
Test case 1: mixture of ip address and subnets
Test case 2: mixture of ip address, subnet and empty input
Test case 3: mixture of ip address, invalid data and subnet