I am having 3 dictionaries in my python code :
self.new_port_dict = {}
# Dictionary to store the new ports
from curr_hostself.old_port_dict = {}
# Dictionary to store the old ports from old_hostself.results_ports_dict = {}
# Holds the result of changed/newly added portsThe script needs to compare what port changed, I am almost there just unable to present help me out :
def comp_ports(self,filename):
try:
f = open(filename)
self.prev_report = pickle.load(f) # NmapReport
for s in self.prev_report.hosts:
self.old_port_dict[s.address] = set()
for x in s.get_open_ports():
self.old_port_dict[s.address].add(x)
for s in self.report.hosts:
self.new_port_dict[s.address] = set()
for x in s.get_open_ports():
self.new_port_dict[s.address].add(x)
print "The following Host/ports were available in old scan : !!"
print `self.old_port_dict`
print "--------------------------------------------------------"
print "The following Host/ports have been added in new scan: !!"
print `self.new_port_dict`
for h in self.old_port_dict.keys():
self.results_ports_dict[h] = self.new_port_dict[h]- self.old_port_dict[h]
print "Result Change: for",h ,"->",self.results_ports_dict[h]
except Exception as l:
print l
This gives a output as :
The following Host/ports were available in old scan : !!
{'172.16.0.41': set([(80, 'tcp'), (666, 'tcp')]), '172.16.0.163': set([(80, 'tcp'), (22, 'tcp')])}
--------------------------------------------------------
The following Host/ports have been added in new scan: !!
{'172.16.0.41': set([(80, 'tcp'), (22, 'tcp')]), '172.16.0.163': set([(80, 'tcp'), (22, 'tcp')])}
Result Change: for 172.16.0.41 -> set([(22, 'tcp')]) From set([(80, 'tcp'), (666, 'tcp')])
Result Change: for 172.16.0.163 -> set([]) From set([(80, 'tcp'), (22, 'tcp')])
As you can clearly see , I have the resulting changed dictionary as well. I want to just print :
For "host_name" , Port changed from "port_id" to "new_port_id"
ex: For 172.16.0.41, Port changed from (666, 'tcp') to (22, 'tcp')
Based on Alex Martelli's answer on Is there a better way to compare dictionary values
You can do this :
#eval the differences between the 2 dict:
diff_key=[key for key in old_port_dict if old_port_dict[key]!=new_port_dict[key]]
for key in diff_key:
print "For %s, Port changed from %s to %s" %(key,old_port_dict[key],new_port_dict[key])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With