-
Notifications
You must be signed in to change notification settings - Fork 87
/
nmap-converter.py
executable file
·228 lines (179 loc) · 8.51 KB
/
nmap-converter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
#!/usr/bin/env python
from libnmap.parser import NmapParser, NmapParserException
from xlsxwriter import Workbook
from datetime import datetime
import os.path
class HostModule():
def __init__(self, host):
self.host = next(iter(host.hostnames), "")
self.ip = host.address
self.port = ""
self.protocol = ""
self.status = ""
self.service = ""
self.tunnel = ""
self.method = ""
self.source = ""
self.confidence = ""
self.reason = ""
self.reason = ""
self.product = ""
self.version = ""
self.extra = ""
self.flagged = "N/A"
self.notes = ""
class ServiceModule(HostModule):
def __init__(self, host, service):
super(ServiceModule, self).__init__(host)
self.host = next(iter(host.hostnames), "")
self.ip = host.address
self.port = service.port
self.protocol = service.protocol
self.status = service.state
self.service = service.service
self.tunnel = service.tunnel
self.method = service.service_dict.get("method", "")
self.source = "scanner"
self.confidence = float(service.service_dict.get("conf", "0")) / 10
self.reason = service.reason
self.product = service.service_dict.get("product", "")
self.version = service.service_dict.get("version", "")
self.extra = service.service_dict.get("extrainfo", "")
self.flagged = "N/A"
self.notes = ""
class HostScriptModule(HostModule):
def __init__(self, host, script):
super(HostScriptModule, self).__init__(host)
self.method = script["id"]
self.source = "script"
self.extra = script.get("output", "").strip()
class ServiceScriptModule(ServiceModule):
def __init__(self, host, service, script):
super(ServiceScriptModule, self).__init__(host, service)
self.source = "script"
self.method = script["id"]
self.extra = script["output"].strip()
def _tgetattr(object, name, default=None):
try:
return getattr(object, name, default)
except Exception:
return default
def generate_summary(workbook, sheet, report):
summary_header = ["Scan", "Command", "Version", "Scan Type", "Started", "Completed", "Hosts Total", "Hosts Up", "Hosts Down"]
summary_body = {"Scan": lambda report: _tgetattr(report, 'basename', 'N/A'),
"Command": lambda report: _tgetattr(report, 'commandline', 'N/A'),
"Version": lambda report: _tgetattr(report, 'version', 'N/A'),
"Scan Type": lambda report: _tgetattr(report, 'scan_type', 'N/A'),
"Started": lambda report: datetime.utcfromtimestamp(_tgetattr(report, 'started', 0)).strftime("%Y-%m-%d %H:%M:%S (UTC)"),
"Completed": lambda report: datetime.utcfromtimestamp(_tgetattr(report, 'endtime', 0)).strftime("%Y-%m-%d %H:%M:%S (UTC)"),
"Hosts Total": lambda report: _tgetattr(report, 'hosts_total', 'N/A'),
"Hosts Up": lambda report: _tgetattr(report, 'hosts_up', 'N/A'),
"Hosts Down": lambda report: _tgetattr(report, 'hosts_down', 'N/A')}
for idx, item in enumerate(summary_header):
sheet.write(0, idx, item, workbook.myformats["fmt_bold"])
for idx, item in enumerate(summary_header):
sheet.write(sheet.lastrow + 1, idx, summary_body[item](report))
sheet.lastrow = sheet.lastrow + 1
def generate_hosts(workbook, sheet, report):
sheet.autofilter("A1:E1")
sheet.freeze_panes(1, 0)
hosts_header = ["Host", "IP", "Status", "Services", "OS"]
hosts_body = {"Host": lambda host: next(iter(host.hostnames), ""),
"IP": lambda host: host.address,
"Status": lambda host: host.status,
"Services": lambda host: len(host.services),
"OS": lambda host: os_class_string(host.os_class_probabilities())}
for idx, item in enumerate(hosts_header):
sheet.write(0, idx, item, workbook.myformats["fmt_bold"])
row = sheet.lastrow
for host in report.hosts:
for idx, item in enumerate(hosts_header):
sheet.write(row + 1, idx, hosts_body[item](host))
row += 1
sheet.lastrow = row
def generate_results(workbook, sheet, report):
sheet.autofilter("A1:N1")
sheet.freeze_panes(1, 0)
results_header = ["Host", "IP", "Port", "Protocol", "Status", "Service", "Tunnel", "Source", "Method", "Confidence", "Reason", "Product", "Version", "Extra", "Flagged", "Notes"]
results_body = {"Host": lambda module: module.host,
"IP": lambda module: module.ip,
"Port": lambda module: module.port,
"Protocol": lambda module: module.protocol,
"Status": lambda module: module.status,
"Service": lambda module: module.service,
"Tunnel": lambda module: module.tunnel,
"Source": lambda module: module.source,
"Method": lambda module: module.method,
"Confidence": lambda module: module.confidence,
"Reason": lambda module: module.reason,
"Product": lambda module: module.product,
"Version": lambda module: module.version,
"Extra": lambda module: module.extra,
"Flagged": lambda module: module.flagged,
"Notes": lambda module: module.notes}
results_format = {"Confidence": workbook.myformats["fmt_conf"]}
print("[+] Processing {}".format(report.summary))
for idx, item in enumerate(results_header):
sheet.write(0, idx, item, workbook.myformats["fmt_bold"])
row = sheet.lastrow
for host in report.hosts:
print("[+] Processing {}".format(host))
for script in host.scripts_results:
module = HostScriptModule(host, script)
for idx, item in enumerate(results_header):
sheet.write(row + 1, idx, results_body[item](module), results_format.get(item, None))
row += 1
for service in host.services:
module = ServiceModule(host, service)
for idx, item in enumerate(results_header):
sheet.write(row + 1, idx, results_body[item](module), results_format.get(item, None))
row += 1
for script in service.scripts_results:
module = ServiceScriptModule(host, service, script)
for idx, item in enumerate(results_header):
sheet.write(row + 1, idx, results_body[item](module), results_format.get(item, None))
row += 1
sheet.data_validation("O2:O${}".format(row + 1), {"validate": "list",
"source": ["Y", "N", "N/A"]})
sheet.lastrow = row
def setup_workbook_formats(workbook):
formats = {"fmt_bold": workbook.add_format({"bold": True}),
"fmt_conf": workbook.add_format()}
formats["fmt_conf"].set_num_format("0%")
return formats
def os_class_string(os_class_array):
return " | ".join(["{0} ({1}%)".format(os_string(osc), osc.accuracy) for osc in os_class_array])
def os_string(os_class):
rval = "{0}, {1}".format(os_class.vendor, os_class.osfamily)
if len(os_class.osgen):
rval += "({0})".format(os_class.osgen)
return rval
def main(reports, workbook):
sheets = {"Summary": generate_summary,
"Hosts": generate_hosts,
"Results": generate_results}
workbook.myformats = setup_workbook_formats(workbook)
for sheet_name, sheet_func in sheets.items():
sheet = workbook.add_worksheet(sheet_name)
sheet.lastrow = 0
for report in reports:
sheet_func(workbook, sheet, report)
workbook.close()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-o", "--output", metavar="XLS", help="path to xlsx output")
parser.add_argument("reports", metavar="XML", nargs="+", help="path to nmap xml report")
args = parser.parse_args()
if args.output == None:
parser.error("Output must be specified")
reports = []
for report in args.reports:
try:
parsed = NmapParser.parse_fromfile(report)
except NmapParserException as ex:
parsed = NmapParser.parse_fromfile(report, incomplete=True)
parsed.basename = os.path.basename(report)
reports.append(parsed)
workbook = Workbook(args.output)
main(reports, workbook)