Skip to content

Instantly share code, notes, and snippets.

@jmacego
Last active April 10, 2022 20:59
Show Gist options
  • Save jmacego/4795cf9ac3ce4cd5cd4b8d232bbdebef to your computer and use it in GitHub Desktop.
Save jmacego/4795cf9ac3ce4cd5cd4b8d232bbdebef to your computer and use it in GitHub Desktop.
Efficiently create a number of subnets out of a larger prefix
#!/bin/env/python
from __future__ import print_function
import ipaddress
def do_vlsm(sorted_vlans):
supernet = input("Supernet: ") or "192.168.224.0/20"
current_subnet = ipaddress.ip_network(supernet)
available_subnets = [current_subnet]
print("\nSubnet Lengths:")
for vlan in sorted_vlans:
if vlan['subnet_len'] == 0:
print("VLAN: {} will not be used.".format(vlan['name']))
else:
tentative_subnet = ''
for x in range(0, 32):
if tentative_subnet:
break
for subnet in available_subnets:
if subnet.prefixlen == vlan['subnet_len'] - x:
tentative_subnet = list(subnet.subnets(new_prefix=vlan['subnet_len']))[0]
available_subnets = (available_subnets
+ list(subnet.address_exclude(tentative_subnet)))
remaining_subnets = []
for a in available_subnets[:]:
if not a.overlaps(tentative_subnet):
remaining_subnets.append(a)
available_subnets = remaining_subnets
vlan['subnet'] = str(tentative_subnet)
break
print("Used Prefixes:")
print("name,vid,prefix")
for vlan in sorted_vlans:
print("{},{},{}".format(vlan['name'], vlan['vlan_id'], vlan['subnet']))
print("Remaining Prefixes:")
for subnet in sorted(available_subnets):
print(subnet)
return sorted_vlans, available_subnets, supernet
def get_vlan_input():
vlans = []
print("Leave VLAN blank when finished")
while(True):
vlan_name = input("VLAN Name: ")
if not vlan_name:
break
vlan_id = input("VLAN ID: ")
if not 1 <= int(vlan_id) <= 4094:
vlan_id = input("VLAN ID must be 1-4094: ")
subnet_len = input("Subnet length: /")
if not 0 <= int(subnet_len) <= 32:
subnet_len = input("Subnet Len must be 0-32: /")
vlans.append({'name': vlan_name, 'subnet_len': int(subnet_len), 'vlan_id': vlan_id})
return sorted(vlans, key=lambda k: k['subnet_len'])
do_vlsm(get_vlan_input())
@jmacego
Copy link
Author

jmacego commented Mar 11, 2019

pip install ipaddress

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment