几天来,我一直在努力寻找解决此解决方案的正确方法,我正在寻求一些帮助。
我有两个文件,需要创建第三个文件来显示关系。
- IP 地址文件 - ip.csv
- 子网文件 - subnet.csv
我需要指定每个 IP 所在的子网,并创建第三个文件
ip.csv 文件将包含大约 150 万个 IP,subnet.csv 文件将包含大约 140,000 个子网。
ip.csv 文件示例:
IP,Type
10.78.175.167,IPv4
10.20.3.56,IPv4
subnet.csv 文件示例:
Subnet,Netmask
10.176.122.136/30,255.255.255.252
10.20.3.0/24,255.255.254.0
我需要创建的文件格式:
Subnet,IP
10.20.3.0/24,10.20.3.56
我试图利用这些页面中的东西:
这是我尝试过的代码。它适用于小型集,但我在使用全套文件运行它时遇到问题。
#!/usr/local/bin/python2.7
import csv
import ipaddress
import iptools
import re
import SubnetTree
import sys
from socket import inet_aton
testdir = '/home/test/testdir/'
iprelfile = testdir + 'relationship.csv'
testipsub = testdir + 'subnet.csv'
testipaddr = testdir + 'ip.csv'
o1 = open (iprelfile, "a")
# Subnet file
IPR = set()
o1.write('Subnet,IP\n')
with open(testipsub, 'rb') as master:
reader = csv.reader(master)
for row in reader:
if 'Subnet' not in row[0]:
# Convert string to unicode to be parsed with ipaddress module
b = unicode(row[1])
# Using ipaddress module to create list containing every IP in subnet
n2 = ipaddress.ip_network(b)
b1 = (list(n2.hosts()))
# IP address file
with open(testipaddr, 'rb') as ipaddy:
readera = csv.reader(ipaddy)
for rowa in readera:
if 'IP' not in rowa[0]:
bb = rowa[0]
for ij in b1:
# Convert to string for comparison
f = str(ij)
# If the IP address is in subnet range
if f == bb:
IPR.update([row[0] + ',' + bb + '\n'])
for ip in IPR:
o1.write(ip + '\n')
# Closing the file
o1.close()