Home > Back-end >  IP Range Script.py Help. Repeating Entries on Output file
IP Range Script.py Help. Repeating Entries on Output file

Time:04-17

The script I'm writing currently with Python is supposed to grab two IP's from a text doc, find the range between the IPS, and then write that output to a new file. I got the script to output what I would like it to, but the problem is it's printing the same IP twice, which will not be efficient as I would like. I believe the problem is with my first regular expression, but I'm open to any suggestions.

import re

def ipRange(start_ip, end_ip):
   start = list(map(int, start_ip.split(".")))
   end = list(map(int, end_ip.split(".")))
   temp = start
   ip_range = []

   ip_range.append(start_ip)
   while temp != end:
      start[3]  = 1
      for i in (3,2):
        if temp[i] == 256:
            temp[i] = 0
            temp[i-1]  = 1
        ip_range.append(".".join(map(str, temp)))
        
    return ip_range
with open(r'AU Sorted IPs') as f:
    fstring = f.readlines()

newFile = open("AU IP Block.txt", "w")    

start_ip = re.compile(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1})')
end_ip = re.compile(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{3})')


for line in fstring:
    ip_range = ipRange(start_ip.search(line).group(), end_ip.search(line).group())

    for ip in ip_range:
        newFile.write((ip) "\n")
        print(ip)

newFile.close()

The output file looks like this:

1.1.1.1 1.1.1.1 1.1.1.2 1.1.1.2 1.1.1.3 1.1.1.3 1.1.1.4 1.1.1.4 etc. I would like the output to not repeat.

CodePudding user response:

You could change the type of ip_range from list to set; the latter does not allow duplicated entries:

def ipRange(start_ip, end_ip):
   start = list(map(int, start_ip.split(".")))
   end = list(map(int, end_ip.split(".")))
   temp = start
   ip_range = set()

   ip_range.add(start_ip)
   while temp != end:
      start[3]  = 1
      for i in (3,2):
        if temp[i] == 256:
            temp[i] = 0
            temp[i-1]  = 1
        ip_range.add(".".join(map(str, temp)))
    
   return ip_range

In this case the output shall be a set with unique entries (ip(s) in this case)

  • Related