Skip to content Skip to sidebar Skip to footer

Editing Csv File To Edit Subnets So There Is No Overlap In IP Ranges (ipaddress Module In Python 3.3)

I have been trying to create a csv file that will change all the subnets and IP address ranges so none overlap. I have this file to start: Zone Name, IPStart, IPStop,Range,Source G

Solution 1:

Both of my issues were solved by reordering the if statements and correctly resetting the iterator. There continues to be issues with the code, but my questions here have been answered.

This is my current code and it works better:

import ipaddress
import csv
from csv import DictReader, DictWriter
from itertools import filterfalse

with open(r'file1.csv', newline='') as fin3,\
     open(r'file2.csv', newline='') as fin4,\
     open(r'file3.csv', 'w', newline='') as fout3:


    read3 = DictReader(fin3) # fin 3 and 4 are copies of the same file
    read4 = DictReader(fin4)

    writenum3 = DictWriter(fout3, fieldnames=read3.fieldnames) 
    writenum3.writeheader()

    lst4=[] # To prevent duplicate lines


    for line3 in read3:
        line3['Range']=ipaddress.ip_network(line3['Range']) # Convert IP ranges to ip network object
        fin4.seek(0) # Reset iterator
        read4 = DictReader(fin4) # Read again to prevent errors
        for line4 in read4:
            line4['Range']=ipaddress.ip_network(line4['Range']) # Convert IP ranges to ip network object
            if line3 not in lst4: # To prevent duplicate lines
                if line3['Range'].overlaps(line4['Range']): # Tests for IP overlap
                    if line3['Range'].netmask < line4['Range'].netmask: # To avoid "Not contained in" errors
                        lst=list(line3['Range'].address_exclude(line4['Range'])) # List of subnets excluding line4 subnet
                        for val in lst:
                            line3['Range']=val # New range
                            line3[' IPStart']=val.network_address #New net address
                            line3[' IPStop']=val.broadcast_address #New broadcast address
                            lst4.append(line3)
                            writenum3.writerow(line3) # Write lines

                    else:
                        lst4.append(line3)
                        writenum3.writerow(line3) # Write lines
                else:
                    lst4.append(line3)
                    writenum3.writerow(line3) # Write lines

Post a Comment for "Editing Csv File To Edit Subnets So There Is No Overlap In IP Ranges (ipaddress Module In Python 3.3)"