Scrub a Messy IP List with Python: Distinct /24 Networks and a From/To Matrix CSV

Scrub a Messy IP List with Python: Distinct /24 Networks and a From/To Matrix CSV
NoBlameNetwork December 1, 2026 5 views 7 min read

A list of IP addresses that has been through three spreadsheets and a change ticket is never clean. Single hosts, CIDR networks and dash ranges sit side by side, half of them appear twice, and somewhere in the middle there is a hostname or a typo. This article gives you a short Python script that takes that list through three steps: it boils the list down to distinct IP addresses, groups those into distinct /24 networks, and writes a two-column from,to CSV that pairs every network with every other one. That last file is what you want when the question is which networks can reach which: every source against every destination. A small add-on lets the script scrub the addresses out of any text at all, such as an email, a ticket or a few lines of config.

What you need: Python 3.6 or newer and a text editor. Everything the script uses (ipaddress, csv, re) ships with Python, so there is nothing to install. Commands are written as python3; on Windows that is usually python or py.

What goes in, what comes out

Your list 1. Distinct IPs 2. Distinct /24s 3. from,to pairs hosts, networks, ranges, repeats one per entry one per network each network to every other 192.168.1.50 10.0.0.0/24 192.168.1.50 192.168.2.10-192.168.2.20 10.0.0.0/24 172.16.0.5 192.168.1.77 10.0.0.1 172.16.0.5 192.168.1.50 192.168.1.77 192.168.2.10 10.0.0.0/24 172.16.0.0/24 192.168.1.0/24 192.168.2.0/24 from,to 10.0.0.0/24,172.16.0.0/24 10.0.0.0/24,192.168.1.0/24 10.0.0.0/24,192.168.2.0/24 172.16.0.0/24,10.0.0.0/24 ... 7 entries 5 addresses 4 networks 12 rows The two repeats are dropped in step 1. The two 192.168.1.x hosts share one /24 in step 2.
Figure 1. The sample list that ships in the script, followed through all three steps.

The work happens in three steps, and each one is a function you can use on its own.

  1. Distinct IPs. Every entry is checked and reduced to one address: a host stays as it is, a network becomes its first usable address, and a range becomes its first address. Repeats are dropped.
  2. Distinct networks. Each address is mapped to the /24 it sits in and repeats are dropped again, so two hosts in the same /24 count once. The prefix length is a setting; /24 is the default.
  3. Pairs. Every network is written against every other network, in both directions and never against itself. Four networks give 12 rows, five give 20.

This is how individual entries are read:

EntryRead asAddress keptNetwork
192.168.1.50single host192.168.1.50192.168.1.0/24
10.0.0.0/24network10.0.0.1, the first usable address10.0.0.0/24
10.0.0.0/255.255.255.0network with a dotted mask10.0.0.110.0.0.0/24
10.0.0.77/24host address with a mask10.0.0.1; it is treated as the network it sits in10.0.0.0/24
10.0.0.128/25network smaller than a /2410.0.0.12910.0.0.0/24
10.50.0.0/16network wider than a /2410.50.0.110.50.0.0/24, its first /24 only
192.168.2.10-192.168.2.20range192.168.2.10, the first address192.168.2.0/24
192.168.2.20-192.168.2.10range typed backwards192.168.2.10192.168.2.0/24
2001:db8::/64IPv6 network2001:db8::12001:db8::/64
web-server-01, 192.168.2.10-20, 10.0.0not an addressnothingnone; the entry is reported on screen and skipped

The script writes two files. The pairs file tells you what to test, and the address file gives you something to test with: a check such as test security-policy-match on a Palo Alto firewall (it is in the PAN-OS CLI cheat sheet) wants one source and one destination address, and the address file holds at least one address from every network in the pairs file.

The script

Save this as network_pairs.py.

import csv
from ipaddress import ip_address, ip_network


def parse_and_deduplicate_ips(inputs):
    """Processes a list of IP addresses, networks, and ranges.

    Returns a distinct list of sorted IP addresses.
    """
    distinct_ips = set()

    for item in inputs:
        item = item.strip()
        if not item:
            continue

        try:
            # 1. Check if it's a Range (e.g., "192.168.1.10-192.168.1.20")
            if "-" in item:
                start_str, end_str = item.split("-", 1)
                start_ip = ip_address(start_str.strip())
                end_ip = ip_address(end_str.strip())

                # Requirement: Use the first IP in the range
                if start_ip <= end_ip:
                    distinct_ips.add(start_ip)
                else:
                    distinct_ips.add(end_ip)

            # 2. Check if it's a Network/CIDR (e.g., "192.168.1.0/24")
            elif "/" in item:
                net = ip_network(item, strict=False)

                # Requirement: Use the first usable IP in the network
                # For standard subnets, net.network_address + 1 is the first usable IP.
                # For /31 or /32 networks, adjust accordingly.
                if net.num_addresses == 1:
                    first_usable = net.network_address
                elif net.num_addresses == 2:
                    first_usable = net.network_address
                else:
                    first_usable = net.network_address + 1

                distinct_ips.add(first_usable)

            # 3. Otherwise, treat as a single host IP (e.g., "192.168.1.50")
            else:
                host_ip = ip_address(item)
                distinct_ips.add(host_ip)

        except (ValueError, TypeError) as e:
            print(f"Skipping invalid entry '{item}': {e}")

    # Sort IPs logically: IPv4 first, then IPv6, each in numeric order
    return sorted(distinct_ips, key=lambda ip: (ip.version, int(ip)))


def to_distinct_networks(ip_list, prefix=24, ipv6_prefix=64):
    """Maps each IP address to the network it sits in.

    Returns a distinct list of sorted networks (/24 by default, /64 for IPv6).
    """
    distinct_networks = set()

    for ip in ip_list:
        length = prefix if ip.version == 4 else ipv6_prefix
        # strict=False drops the host bits: 192.168.1.50/24 -> 192.168.1.0/24
        distinct_networks.add(ip_network(f"{ip}/{length}", strict=False))

    # Sort networks logically: IPv4 first, then IPv6, each in numeric order
    return sorted(
        distinct_networks,
        key=lambda net: (net.version, int(net.network_address)),
    )


def save_to_csv(ip_list, filename="network_ips.csv"):
    """Saves the distinct list of IPs into a CSV file."""
    with open(filename, mode="w", newline="", encoding="utf-8") as file:
        writer = csv.writer(file)
        writer.writerow(["IP Address"])  # CSV Header
        for ip in ip_list:
            writer.writerow([str(ip)])
    print(f"Successfully exported {len(ip_list)} distinct IPs to '{filename}'.")


def save_pairs_to_csv(networks, filename="network_pairs.csv"):
    """Saves every network paired with every other network (from, to)."""
    pair_count = 0
    with open(filename, mode="w", newline="", encoding="utf-8") as file:
        writer = csv.writer(file)
        writer.writerow(["from", "to"])  # CSV Header
        for source in networks:
            for destination in networks:
                # No network to itself, and no IPv4 to IPv6
                if source == destination or source.version != destination.version:
                    continue
                writer.writerow([str(source), str(destination)])
                pair_count += 1
    print(f"Successfully exported {pair_count} network pairs to '{filename}'.")


# --- Example Usage ---
if __name__ == "__main__":
    # Mix of single hosts, CIDR networks, IP ranges, and intentional duplicates
    sample_inputs = [
        "192.168.1.50",  # Single host
        "10.0.0.0/24",  # Network -> Uses first usable (10.0.0.1)
        "192.168.1.50",  # Duplicate host
        "192.168.2.10-192.168.2.20",  # Range -> Uses first IP (192.168.2.10)
        "10.0.0.0/24",  # Duplicate network
        "172.16.0.5",  # Single host
        "192.168.1.77",  # Another host in the same /24 as 192.168.1.50
    ]

    print("Processing network inputs...")

    # Step 1: one distinct IP per entry
    processed_ips = parse_and_deduplicate_ips(sample_inputs)
    save_to_csv(processed_ips, "distinct_network_ips.csv")

    # Step 2: the distinct /24 networks those IPs sit in
    networks = to_distinct_networks(processed_ips, prefix=24)
    print(f"{len(processed_ips)} distinct IPs sit in {len(networks)} networks.")

    # Step 3: every network paired with every other network
    save_pairs_to_csv(networks, "network_pairs.csv")

Run it

As written, the script works through the seven sample entries at the bottom of the file, which is a quick way to see that it runs on your machine.

python3 network_pairs.py
Processing network inputs...
Successfully exported 5 distinct IPs to 'distinct_network_ips.csv'.
5 distinct IPs sit in 4 networks.
Successfully exported 12 network pairs to 'network_pairs.csv'.

Seven entries became five addresses: the repeated host and the repeated network are gone, the /24 became its first usable address and the range became its first address. Those five addresses sit in four /24 networks, because 192.168.1.50 and 192.168.1.77 share one, and four networks make twelve pairs. Both files land in the folder you ran the script from. distinct_network_ips.csv is the address list:

IP Address
10.0.0.1
172.16.0.5
192.168.1.50
192.168.1.77
192.168.2.10

and network_pairs.csv is the matrix, each network as a source against every other network as a destination:

from,to
10.0.0.0/24,172.16.0.0/24
10.0.0.0/24,192.168.1.0/24
10.0.0.0/24,192.168.2.0/24
172.16.0.0/24,10.0.0.0/24
172.16.0.0/24,192.168.1.0/24
172.16.0.0/24,192.168.2.0/24
192.168.1.0/24,10.0.0.0/24
192.168.1.0/24,172.16.0.0/24
192.168.1.0/24,192.168.2.0/24
192.168.2.0/24,10.0.0.0/24
192.168.2.0/24,172.16.0.0/24
192.168.2.0/24,192.168.1.0/24

To send the files somewhere else, change the two file names near the end of the script.

How it works

  1. Sort the entries by punctuation. A dash means a range, a slash means a network, and anything else is treated as a single host. The checks run in that order.
  2. Let ipaddress do the validating. ip_address() and ip_network() raise an error for anything that is not a real address, and the except turns that error into a Skipping invalid entry line where it would otherwise stop the script. strict=False is what lets a host address with a mask, such as 10.0.0.77/24, through as the network it belongs to.
  3. Keep one address per entry. For a range it is the lower of the two ends, so a range typed backwards still works. For a network it is the network address plus one. Two sizes are special: a /32 holds a single address, and a /31 is a point-to-point link whose two addresses are both usable (RFC 3021), so for those the network address itself is kept.
  4. De-duplicate, then sort. The addresses are collected in a set, which cannot hold the same value twice. The sort key is the IP version followed by the address as a number, which puts IPv4 ahead of IPv6 and 10.0.0.9 ahead of 10.0.0.10. A plain text sort gets the second of those wrong.
  5. Map each address to its network. ip_network() is given the address with /24 on the end, and strict=False makes it drop the host bits, so 192.168.1.50 becomes 192.168.1.0/24. The networks go into a set as well, which is why two hosts in one /24 count once. IPv6 addresses are grouped by /64.
  6. Pair them up. Two nested loops walk the sorted list of networks: the outer loop picks the source and the inner loop offers every destination. A network is never paired with itself, and an IPv4 network is never paired with an IPv6 one.

Change the network size

The /24 is an argument, not a rule. To group by /16, change one number in the call near the end of the script:

    networks = to_distinct_networks(processed_ips, prefix=16)

With prefix=32 nothing is grouped at all: every address stays on its own as a /32, and the pairs file becomes a host-to-host matrix.

Feed it your own list

The sample entries are only there to prove the script runs. For real work, put your entries in a text file, one per line (commas work too), and replace everything from the # --- Example Usage --- line down with this:

import sys

if __name__ == "__main__":
    source_file = sys.argv[1] if len(sys.argv) > 1 else "ips.txt"

    with open(source_file, encoding="utf-8-sig") as f:
        # One entry per line; commas work as separators too
        entries = f.read().replace(",", "\n").splitlines()

    processed_ips = parse_and_deduplicate_ips(entries)
    save_to_csv(processed_ips, "distinct_network_ips.csv")

    networks = to_distinct_networks(processed_ips, prefix=24)
    print(f"{len(processed_ips)} distinct IPs sit in {len(networks)} networks.")

    save_pairs_to_csv(networks, "network_pairs.csv")

Then name the file when you run the script. With no file name it looks for ips.txt in the current folder.

python3 network_pairs.py ips.txt

Here is a list in the state these lists usually arrive in:

192.168.1.50
10.0.0.0/24
192.168.1.50
192.168.2.10-192.168.2.20
10.0.0.0/24, 172.16.0.5
192.168.1.77
10.20.30.77/24

web-server-01
192.168.2.10-20

And here is what the script makes of it:

Skipping invalid entry 'web-server-01': 'web' does not appear to be an IPv4 or IPv6 address
Skipping invalid entry '192.168.2.10-20': '20' does not appear to be an IPv4 or IPv6 address
Successfully exported 6 distinct IPs to 'distinct_network_ips.csv'.
6 distinct IPs sit in 5 networks.
Successfully exported 20 network pairs to 'network_pairs.csv'.

Ten lines, six addresses, five networks, twenty pairs. The two entries the script could not use are named along with the reason. Blank lines are the one thing it drops without comment, so nothing else disappears without you seeing it. network_pairs.csv starts like this and carries on in the same pattern for all twenty rows:

from,to
10.0.0.0/24,10.20.30.0/24
10.0.0.0/24,172.16.0.0/24
10.0.0.0/24,192.168.1.0/24
10.0.0.0/24,192.168.2.0/24
10.20.30.0/24,10.0.0.0/24
10.20.30.0/24,172.16.0.0/24
10.20.30.0/24,192.168.1.0/24
10.20.30.0/24,192.168.2.0/24

The utf-8-sig encoding is there for files saved on Windows: some tools put an invisible marker at the start of a text file, and without that setting the first entry of such a file would be rejected.

Scrub addresses out of any text

A list is the easy case. More often the addresses are buried in something else: an email thread, a change ticket, a firewall log, a slice of running config, or the route tables saved in the Panorama API walkthrough. A regular expression can pull out everything that looks like an IPv4 host, network or range and pass it to the same functions. Use this block in place of the previous one:

import re
import sys

# An IPv4 address, optionally followed by /prefix or by "-" and a second address
IP_PATTERN = re.compile(r"""
    (?<![\w.])                  # not glued to a longer token
    \d{1,3}(?:\.\d{1,3}){3}     # 192.168.1.50
    (?:
        /\d{1,2}                # then maybe /24
      | [ \t]*-[ \t]*\d{1,3}(?:\.\d{1,3}){3}    # or "-" and a second address
    )?
    (?!\.?\d)                   # and no more digits straight after
""", re.VERBOSE)

if __name__ == "__main__":
    source_file = sys.argv[1] if len(sys.argv) > 1 else "ips.txt"

    with open(source_file, encoding="utf-8-sig") as f:
        found = IP_PATTERN.findall(f.read())

    # Subnet masks and wildcard masks look like addresses; leave them out
    entries = [e for e in found if not e.startswith(("255.", "0."))]

    processed_ips = parse_and_deduplicate_ips(entries)
    save_to_csv(processed_ips, "distinct_network_ips.csv")

    networks = to_distinct_networks(processed_ips, prefix=24)
    print(f"{len(processed_ips)} distinct IPs sit in {len(networks)} networks.")

    save_pairs_to_csv(networks, "network_pairs.csv")

Given a file like this:

CHG-1042: allow HTTPS from the web tier (10.20.30.0/24) to the database
VIP at 10.40.5.17. Jump hosts 10.1.1.10 - 10.1.1.14 keep their SSH access.
The old rule also listed 10.40.5.17, 10.20.30.0/24 and 300.1.1.1 (typo?).

interface Vlan30
 ip address 10.20.30.1 255.255.255.0

it prints one warning and finds three networks:

Skipping invalid entry '300.1.1.1': '300.1.1.1' does not appear to be an IPv4 or IPv6 address
Successfully exported 3 distinct IPs to 'distinct_network_ips.csv'.
3 distinct IPs sit in 3 networks.
Successfully exported 6 network pairs to 'network_pairs.csv'.
from,to
10.1.1.0/24,10.20.30.0/24
10.1.1.0/24,10.40.5.0/24
10.20.30.0/24,10.1.1.0/24
10.20.30.0/24,10.40.5.0/24
10.40.5.0/24,10.1.1.0/24
10.40.5.0/24,10.20.30.0/24

The web tier's /24 and the interface address 10.20.30.1 count once, because the first usable address of 10.20.30.0/24 is 10.20.30.1. The VIP that was mentioned twice appears once, the jump-host range became its first address, the subnet mask was left out, and the impossible 300.1.1.1 was reported, not quietly lost.

Pulling addresses out of free text is guesswork by nature, so know where this version draws its lines:

  • IPv4 only. IPv6 has too many written forms for a short pattern. Put IPv6 entries in a list and use the list version above, which handles them.
  • Anything shaped like an address is collected. A four-part software version such as 10.2.3.4 looks exactly like an address and will be treated as one. Numbers that cannot be addresses, like 300.1.1.1, are caught by the validation and reported.
  • Masks are filtered, crudely. The line that drops everything starting with 255. or 0. keeps subnet masks and wildcard masks (255.255.255.0, 0.0.0.255) out of the result. It also drops a default route written as 0.0.0.0/0.
  • A dash between two addresses means a range. 10.1.1.10 - 10.1.1.14 becomes 10.1.1.10. So does a source and destination pair that somebody wrote with a dash between them.

Things worth knowing

  • The pairs file grows fast. The row count is the number of networks multiplied by one less than that number: 10 networks give 90 rows, 100 give 9,900 and 1,000 give 999,000. Excel opens 1,048,576 rows at most, so much past a thousand networks the file no longer fits in a spreadsheet.
  • A network wider than a /24 counts as its first /24. The script keeps one address per entry, so 10.50.0.0/16 turns into 10.50.0.1 and then into 10.50.0.0/24. The other 255 /24s inside it are not in the matrix. If you want them, see the change below.
  • A range counts as the /24 its first address is in. 10.0.0.250-10.0.1.5 crosses into a second /24, but only 10.0.0.0/24 is recorded. Add the second network as its own entry if you need it.
  • Duplicates are judged on the result. 10.0.0.0/24, 10.0.0.77/24 and the host 10.0.0.1 all come out as the address 10.0.0.1. Neither file records which entry produced which row.
  • Ranges need both ends in full. 192.168.2.10-20 is reported as invalid. Write 192.168.2.10-192.168.2.20.
  • Names are not resolved. The script never touches DNS. A hostname is reported and skipped.
  • A default route becomes 0.0.0.0/24. 0.0.0.0/0 is a valid network, its first usable address is 0.0.0.1, and that lands in the matrix as a network nobody owns. Take default routes out of a list before you run it; the free-text version already filters them.
  • IPv6 works in the list version. Hosts, networks and ranges are all accepted, sorted after the IPv4 entries, grouped by /64 and paired only with other IPv6 networks.

To put every /24 of a wider block into the matrix, replace the line distinct_ips.add(first_usable) with these six, keeping the indentation:

                if net.version == 4 and net.prefixlen < 24:
                    # One address for every /24 inside a wider block
                    for sub in net.subnets(new_prefix=24):
                        distinct_ips.add(sub.network_address + 1)
                else:
                    distinct_ips.add(first_usable)

A /16 then contributes 256 networks. Remember the first point in the list above: 256 networks on their own are 65,280 pairs.

Key takeaways

The standard library's ipaddress module does the hard part: it validates every entry and understands hosts, networks and both IP versions. The script keeps one address per entry (the first of a range, the first usable of a network), maps each address to its /24, and uses a set at both stages so repeats disappear. Two nested loops then write every network against every other as from,to rows, which is n × (n − 1) rows for n networks. Read a list from a file when you want every bad line reported; use the regular expression when the addresses are buried in other text. Change prefix=24 when a /24 is the wrong size, and remember that anything wider than the prefix is represented by its first network only.
Discuss this article on Reddit

Found it useful, spotted a mistake, or done it differently? Start a thread. The link and title are filled in for you; Reddit will ask you to confirm before it posts.