如何使用python过滤ip public和ip private

时间:2017-09-29 07:31:10

标签: python

我有一个文件(list_ip.txt),它只包含公共ip列表和ip private。我想将一个文件拆分为2个文件。一个文件(ip_public.txt)包含公共IP,一个文件(ip_private.txt)再次包含ip private。我该怎么做? ip_list.txt的内容:

192.168.14.43
104.244.xxx.xxx
192.168.10.54
38.102.xxx.xxx
192.168.13.232
144.217.xxx.xxx
10.100.40.93
54.171.xxx.xxx
10.100.xxx.xxx
183.61.xxx.xxx
10.100.xxx.xxx
136.243.xxx.xxx
10.40.xxx.xxx
185.75.xxx.xxx

这是我的代码:

import csv

file = open('list_ip.txt', 'r')
ipprivate = open('ip_private.txt', 'w')
ippublic = open('ip_public.txt', 'w')

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

    for i in range(4):
        if start[i] > end[i]:
            start, end = end, start
        break

    temp = start
    ip_range = []

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

    return ip_range

iprange = ipRange("192.168.0.0","192.168.255.255")
iprange2 = ipRange("172.16.0.0","172.31.255.255")
iprange3 = ipRange("10.0.0.0","10.255.255.255")

for line in file:
    if line == iprange:
        ipprivate.write(line)
    if line == iprange2:
        ipprivate.write(line)
    if line == iprange3:
        ipprivate.write(line
    else:
        ippublic.write(line)
file.close()
ipprivate.close()
ippublic.close()

1 个答案:

答案 0 :(得分:1)

您只需检查IP是否属于专用IP地址空间范围。 private ip range

这很简单。这是一个例子(考虑到IP在不同的行上):

allfp = open('all.txt')
publicfp = open('public.txt', 'w')
privatefp = open('private.txt', 'w')

def is_public_ip(ip):
    ip = list(map(int, ip.strip().split('.')[:2]))
    if ip[0] == 10: return False
    if ip[0] == 172 and ip[1] in range(16, 32): return False
    if ip[0] == 192 and ip[1] == 168: return False
    return True

for line in allfp:
    if is_public_ip(line):
        publicfp.write(line)
    else:
        privatefp.write(line)

allfp.close()
publicfp.close()
privatefp.close()

编辑:此代码假定输入文件的内容是有效的IP地址,因此不会检查IP的有效性。