如果它们通过Python 2.7和netaddr模块与子网匹配,我试图获取IP地址列表。
我目前正在使用从www.python.org网站安装Python 2.7的Windows PC上运行它。
我打算在安装了python 2.7的RHEL 6.x上运行它。
这应该从ip_list
获取IP地址并将其与banned_subnets
进行比较
如果找到匹配项,则应将其添加到new_list
并打印出Match found
。
应该有两场比赛
10.11.117.137 is in subnet 10.11.117.0/24
10.24.33.21 is in subnet 10.24.33.0/24
我无法根据具有多个值的列表检查列表中的多个值。
我已阅读netaddr
上的文档,我已阅读本网站上的Python - Comparing two lists以及其他几个,但我只是没有得到它。
以下是我想要开始工作的一些代码
import netaddr
# Range of IP Addresses that we see connections from.
ip_list = ['10.11.117.137', '10.11.122.20', '10.24.33.21', '10.11.122.22']
# List of IP Subnets that members of IP list should not be from.
banned_subnets = ['10.11.117.0/24', '10.24.33.0/24']
# Using banned_subnets as our master list see if any of the ip_list addresses are present
# If they are present print the ip address
new_list = []
for Z in banned_subnets:
for X in ip_list:
if netaddr.IPAddress(X) == netaddr.IPNetwork(Z):
new_list.append(X)
print 'Match Found'
else:
print 'No Matches Found'
print new_list
当我运行这个时,我得到以下返回的
E:\Python27\python.exe E:/Users/twelsh/PycharmProjects/lool/liist-loop.py
Match Found
Match Found
Match Found
Match Found
Match Found
Match Found
Match Found
Match Found
['10.11.117.137', '10.11.122.20', '10.24.33.21', '10.11.122.22', '10.11.117.137', '10.11.122.20', '10.24.33.21', '10.11.122.22']
Process finished with exit code 0
我是所有这些Python malarky的新手。所有建议都将不胜感激。
答案 0 :(得分:1)
将intersection
设置为&
运算符,并将结果保存到列表中。
new_list = [str(ip) for ip in netaddr.IPSet(ip_list) & (netaddr.IPSet(banned_subnets))]
print new_list