如何从文件中的CIDR生成所有IP?

时间:2019-01-15 03:37:56

标签: python

我有一个带有CIDR的文件,如下所示:

1.2.3.4/10
5.6.7.8/20
...

我想读取CIDR文件,然后将所有IP写入另一个文件。

已经尝试过此python代码,但不知道如何读取每一行,然后执行此操作:

from netaddr import *

f = open("everyip.txt", "w")
ip = IPNetwork('10.0.0.0/8')

for addr in ip:
    f.write(str(addr) + '\n')

f.close()

编辑

我也已经尝试过:

from netaddr import *

f = open("everyip.txt", "w")

with open("cidrs.txt") as f:
  content = f.readlines()
  content = [x.strip() for x in content] 
  str1 = ''.join(content)
  ip = IPNetwork(str1)

for addr in ip:
  f.write(str(addr) + '\n')

f.close()

这仅适用于cidrs.txt中的1行。如果cidrs.txt中有多于1行,则会引发错误并且不起作用。

编辑2:

我尝试了此操作,但收到错误消息:

from netaddr import *
i = 0
f = open("everyip.txt", "w")
with open("range.txt") as f1:
    content = f1.readlines()
    content = [x.strip() for x in content]
    while (i < len(content)):
        ip = IPNetwork(content[i])
        for addr in ip:
            f.write(str(addr) + '\n')
        f.close()

错误:

f.write(str(addr) + '\n')
ValueError: I/O operation on closed file.

1 个答案:

答案 0 :(得分:1)

OP将其发布为对他们问题的修改。

已修复:

from netaddr import *
with open("range.txt") as f1:
    content = f1.readlines()
    content = [x.strip() for x in content]
    with open("everyip.txt", "w") as f:
        for i in content:
            ip = IPNetwork(i)
            for addr in ip:
                f.write(str(addr) + '\n')

如果有很多行,最好一次处理一行,而不是将它们全部读入内存。

from netaddr import *
with open("range.txt") as f1, open("everyip.txt", "w") as f:
    for line in f1:
        cidr = line.rstrip('\n')
        ip = IPNetwork(cidr)
        for addr in ip:
            f.write(str(addr) + '\n')