Next we just need to restructure the data into a useful format, in
this case we'll put collect the strings together and then dump it
as json format.
By using json it is ready for more advanced
manipulations in the future. Further atomization of the data is
possible too, but sticking with our original plan is a good
example to begin with.
Remember the two levels of data we want to collect: host level and
service/port level, stored in the following as
host_state and port_state.
import nmap, json, time def scan(host='127.0.0.1',range='22-80'): '''Setup port scanner''' nm = nmap.PortScanner() nm.scan(host, range) return nm nm = scan() for host in nm.all_hosts(): host_state = {} host_state["host"] = host host_state["state"] = nm[host].state() for proto in nm[host].all_protocols(): for port in nm[host][proto].keys(): port_state = nm[host][proto][port] port_state["host"] = host port_state["protocol"] = proto port_state["port"] = port timestamp = time.time() host_state["timestamp"] = str(timestamp) port_state["timestamp"] = str(timestamp) print json.dumps(host_state) print json.dumps(port_state) docid = str(host) + ":" + str(proto) + ":" + str(port) + ":" + str(port_state["timestamp"])
In addition to a few more lines of code, note specifically that
you must now import json and
time modules. We also remove all the verbose
print lines and only print the resulting json
string instead. The docid variable is also
created, which will be used for the membase document key in the
next step.
You can download the script from: nmap-tutorial-collect.py