我写了一个端口扫描器,它基本上将新的扫描结果与以前的扫描结果进行比较,然后找到哪些端口已更改/got_add/got_deleted。
比较端口变化的方法如下:
def comp_ports(self,filename):
try:
f = open(filename)
self.prev_report = pickle.load(f) # NmapReport
self.old_port_dict = collections.defaultdict(set)
for s in self.prev_report.hosts:
for x in s.get_open_ports():
self.old_port_dict[s.address].add(x)
self.new_port_dict = collections.defaultdict(set)
for s in self.report.hosts:
for x in s.get_open_ports():
self.new_port_dict[s.address].add(x)
hosts = sorted(set(self.old_port_dict) | set(self.new_port_dict))
scan_same = dict()
scan_new = dict()
scan_del = dict()
prev_set = set(self.prev_report.hosts)
new_set = set(self.report.hosts)
scan_same = prev_set & new_set
scan_new = new_set - prev_set
scan_del = prev_set - new_set
print()
print('-' * 10, 'Same')
for host, ports in scan_same.items():
print(host, ':')
for port in ports:
print(':::', port[0], '/', port[1])
print()
print('*' * 10, 'Added')
for host, ports in scan_new().items():
print(host, ':')
for port in ports:
print(':::', port[0], '/', port[1])
print()
print('=' * 10, 'Deleted')
for host, ports in scan_del().items():
print(host, ':')
for port in ports:
print(':::', port[0], '/', port[1])
except Exception as l:
print l
raise
根据答案,但这会引发新的异常:
'set' object has no attribute 'items'
Traceback (most recent call last):
File "portwatch.py", line 316, in <module>
report.comp_ports(config.get('system','scan_directory') + '/nmap-report-old.pkl')
File "portwatch.py", line 159, in comp_ports
for host, ports in scan_same.items():
AttributeError: 'set' object has no attribute 'items'
我如何迭代?