【问题标题】:python extract ip-addresse cidre/-ranges into individual ip-addressespython将ip-address cidr/-ranges提取到单独的ip-addresses中
【发布时间】:2015-07-09 00:07:53
【问题描述】:

我是 python 新手。我想在python中扫描ip地址,为此我想读取一个带有不同表示法的ip地址的文件,比如cidr或range,脚本应该将ip cidr/ranges提取到单独的ip地址中。

file_in = open("test.txt", "r")
file_out = open("ip-test2.txt","w")
i = 1
for line in file_in:
    #take the line and look if that is a individual ip , if not make block of ip-    
addresses and write them into a new file_out
    file_out.write(str(i) + ": " + line)
    i = i + 1
file_out.close()
file_in.close()

知道怎么做吗?或者我可以使用哪个工具?

【问题讨论】:

  • Regex 听起来像是您需要的工具。也许......输入文件的样本以及您想要的输出类型会有所帮助。
  • 你能给我们举几个文件的例子吗? netaddr 包使用非常广泛。
  • @lanhance 一个例子 192.168.132.197/30 192.168.132.123-125 192.0.2.0 并在 output_file 我想要 192.168.132.197 192.168.132.198 192.168 .132.123 192.168.132.124 192.168.132.125 192.0.2.0 所以我得到了所有 ips 个人
  • @Ben 谢谢 :) netaddr 效果很好。我希望范围的功能并不多,但我认为我可以将范围更改为单独的 ips 手册。

标签: python python-2.7 ip-address cidr


【解决方案1】:

我想你会发现python-iptools 包可以满足你的需求。基本上是这样的:

with open("test.txt", "r") as file_in:
    ips_and_ranges = IpRangeList(file_in.readlines())

with open("ip-test2.txt","w") as file_out:
    for ip in ips_and_ranges:
        file_out.write(ip)

假设 file_in 的大小合理,否则您可能需要分块读取它。

更新:我的初始代码需要一个“splat”来将列表解压缩到 args 中,并删除换行符(因此,“基本上”:P)。此外,要处理像“10.1.1.1-255”这样的范围,需要对数据进行一些处理; iptools 支持将这样的范围作为一个元组。假设这样的范围只出现在最后一个八位字节中,这可行:

from iptools import IpRangeList

def clean(ip_string):

    ret = ip_string.strip()
    if "-" in ret:
        parts = ret.split("-")
        ret = (parts[0], ret.rsplit(".", 1)[0] + "." + parts[1])

    return ret

with open("test.txt", "r") as file_in:
    in_list = [clean(x) for x in file_in.readlines()]

ips_and_ranges = IpRangeList(*in_list)

with open("ip-test2.txt", "w") as file_out:
    for ip in ips_and_ranges:
        file_out.write(ip)

【讨论】:

  • 我得到以下异常Traceback (most recent call last): File "SHA1Scanner.py", line 23, in <module> ips_and_ranges = IpRangeList(file_in.readlines()) File "/Library/Python/2.7/site-packages/iptools/__init__.py", line 410, in __init__ self.ips = tuple(map(IpRange, args)) File "/Library/Python/2.7/site-packages/iptools/__init__.py", line 142, in __init__ elif ipv4.validate_cidr(start): File "/Library/Python/2.7/site-packages/iptools/ipv4.py", line 260, in validate_cidr if _CIDR_RE.match(s): TypeError: expected string or buffer
  • 它需要一个“splat” (*) 来将列表解压缩为构造函数的参数。请参阅我的更新答案。
猜你喜欢
  • 2016-04-26
  • 1970-01-01
  • 2011-10-06
  • 2023-03-28
  • 2021-11-16
  • 2018-04-12
  • 2012-11-04
  • 1970-01-01
  • 2017-08-23
相关资源
最近更新 更多