【问题标题】:How to filter ip public and ip private with python [duplicate]如何使用python过滤ip public和ip private [重复]
【发布时间】:2018-03-11 01:38:38
【问题描述】:

我有一个文件 (list_ip.txt),其中仅包含公共 ip 列表和 ip 私人。我想将一个文件分成两个文件。一个文件 (ip_public.txt) 包含公共 ip,一个文件 (ip_private.txt) 再次包含 ip 私有。我该怎么做? 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()

【问题讨论】:

  • 显示部分内容。我们不知道这是如何格式化的。
  • 到目前为止你尝试过什么?似乎您希望 SO 社区为您工作而无需自己尝试。您应该通过提供您遇到的问题来使您的问题更加具体。
  • 输入文件的样本可能很有用。谢谢!
  • @vishes_shell 我试过了,我会编辑并输入我创建的代码
  • @RaúlReguilloCarmona 简短地说,我会编辑这篇文章

标签: python


【解决方案1】:

您只需检查 IP 是否在私有 IP 地址空间的范围内。

这很简单。这是一个示例(考虑到 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 的有效性。

【讨论】:

  • 谢谢先生,它的代码可以工作。但我每个人都很困惑为什么应该有参数 list(map(int, ip.strip().split('.'))) ?
  • 它将字符串ip拆分为4个,并将它们转换为整数进行比较。
  • 哦,意思是当 ip 192.168.1.1 在 split based (.) 中分成 4 部分。如果第一部分 == 192,那么它将进入第二部分。如果第二部分 == 168 它将立即自动属于 ip private。如果第一部分和第二部分不等于 192 和 168,那么它将自动属于 ip public。谢谢大佬解释
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-25
  • 1970-01-01
  • 1970-01-01
  • 2012-06-24
相关资源
最近更新 更多