我正在写两个字典。第一个字典“黑名单”包含地址作为键,而日期则作为值。第二个词典“已转移”还包含地址(作为关键字)和日期(作为值)。我想比较两个字典,以检查是否有任何“已转移”地址在“黑名单”地址中。如果有匹配项,我想检查黑名单上的日期是在转移日期之前还是之后。我希望它创建一个新字典“ update”,并将地址作为键,值视情况而定为“ before”或“ after”。
请注意,“ 94.142.136.0/21”匹配“ 94.142.136.190”
blacklist = {'93.118.36.235': '25/02/2016', '62.149.128.160': '05/06/2017', '62.149.128.163': '05/06/2017', '62.149.128.166': '05/06/2017', '62.149.128.72': '05/06/2017', '62.149.128.74': '05/06/2017', '69.163.171.33': '10/03/2014', '69.163.200.61': '22/12/2014', '94.142.136.190': '19/02/2016'}
transferred ={'94.142.136.0/21': '28/06/2019', '185.2.4.0/22': '01/07/2019', '213.158.64.0/19': '01/07/2019', '5.154.240.0/24': '01/07/2019', '78.159.140.0/22': '01/07/2019', '81.88.48.0/20': '01/07/2019'}
found = {}
for k,v in blacklist.items():
for k1,v1 in transferred.items():
if k1 = k:
if v1 > v:
found.append(k1, 'before')
else:
found.append(k1, 'after')
我希望这是结果
found = {'94.142.136.0/21': 'before'}
答案 0 :(得分:1)
首先,您需要检查blacklist
词典中的IP地址是否在transferred
词典中的CIDR块之一中。然后,您需要将这些日期字符串转换为datetime
对象,以便进行比较
from ipaddress import ip_address, ip_network
from datetime import date
blacklist = {'93.118.36.235': '25/02/2016', '62.149.128.160': '05/06/2017', '62.149.128.163': '05/06/2017', '62.149.128.166': '05/06/2017', '62.149.128.72': '05/06/2017', '62.149.128.74': '05/06/2017', '69.163.171.33': '10/03/2014', '69.163.200.61': '22/12/2014', '94.142.136.190': '19/02/2016'}
transferred ={'94.142.136.0/21': '28/06/2019', '185.2.4.0/22': '01/07/2019', '213.158.64.0/19': '01/07/2019', '5.154.240.0/24': '01/07/2019', '78.159.140.0/22': '01/07/2019', '81.88.48.0/20': '01/07/2019'}
found = {}
for ip_addr in blacklist:
for cidr_block in transferred:
if ip_address(ip_addr) in ip_network(cidr_block):
blacklist_date = date(*map(int,blacklist[ip_addr].split("/")[::-1]))
transferred_date = date(*map(int,transferred[cidr_block].split("/")[::-1]))
if transferred_date > blacklist_date:
found[cidr_block] = 'before'
else:
found[cidr_block] = 'after'
print(found)
答案 1 :(得分:0)
使用这些方法转换格式,检查它们是否相等。
import socket,struct
def makeMask(n):
"return a mask of n bits as a long integer"
return (2L<<n-1) - 1
def dottedQuadToNum(ip):#Pass just 94.142.136.190
"convert decimal dotted quad string to long integer"
return struct.unpack('L',socket.inet_aton(ip))[0]
def networkMask(ip,bits):#Pass 94.142.136.0 and 21
"Convert a network address to a long integer"
return dottedQuadToNum(ip) & makeMask(bits)
答案 2 :(得分:0)
ipaddress模块似乎可以满足您的要求: [] https://docs.python.org/3/library/ipaddress.html
from ipaddress import ip_network, ip_address
found = {}
for k,v in blacklist.items():
for k1,v1 in transferred.items():
if ip_address(k) in ip_network(k1):
found[k1] = 'before' if v1 > v else 'after'