22import xml .etree .ElementTree as ET
33from typing import Dict , List
44
5+
56class NmapOriginalFormat (Enum ):
67 NORMAL = 1
78 XML = 2
89 GREPABLE = 3
910 LOOKS_INVALID = 10
1011
12+
1113def detect_format (nmap_original_output : str ) -> NmapOriginalFormat :
1214 if nmap_original_output .find ("Starting Nmap " ) >= 0 :
1315 return NmapOriginalFormat .NORMAL
@@ -17,6 +19,7 @@ def detect_format(nmap_original_output: str) -> NmapOriginalFormat:
1719 return NmapOriginalFormat .GREPABLE
1820 return NmapOriginalFormat .LOOKS_INVALID
1921
22+
2023def reformat_to_markdown (nmap_original_output : str ) -> str :
2124 if detect_format (nmap_original_output ) == NmapOriginalFormat .LOOKS_INVALID :
2225 raise ValueError ("The provided input looks invalid" )
@@ -29,39 +32,39 @@ def reformat_to_markdown(nmap_original_output: str) -> str:
2932 raise NotImplementedError ("Only XML input is supported for now" )
3033 return reformat_dict_to_markdown (nmap_open_ports )
3134
35+
3236def reformat_xml_to_dict (nmap_original_output : str ) -> dict :
33- """Parse Nmap XML output and return a dict of address -> sorted list of open ports (ints).
34- """
37+ """Parse Nmap XML output and return a dict of address -> sorted list of open ports (ints)."""
3538 try :
3639 root = ET .fromstring (nmap_original_output )
3740 except ET .ParseError as exc :
3841 raise ValueError (f"Failed to parse XML input: { exc } " )
3942
4043 hosts_ports : Dict [str , set ] = {}
4144
42- for host in root .findall (' host' ):
43- addrs = [a .get (' addr' ) for a in host .findall (' address' ) if a .get (' addr' )]
45+ for host in root .findall (" host" ):
46+ addrs = [a .get (" addr" ) for a in host .findall (" address" ) if a .get (" addr" )]
4447 if not addrs :
4548 continue
4649
4750 # Sort addresses
4851 addrs .sort ()
4952
5053 # Join into a comma-separated string
51- addr = ',' .join (addrs )
54+ addr = "," .join (addrs )
5255
5356 # find ports
54- ports_elem = host .find (' ports' )
57+ ports_elem = host .find (" ports" )
5558 if ports_elem is None :
5659 continue
5760
58- for port in ports_elem .findall (' port' ):
59- state = port .find (' state' )
61+ for port in ports_elem .findall (" port" ):
62+ state = port .find (" state" )
6063 if state is None :
6164 continue
62- if state .get (' state' ) != ' open' :
65+ if state .get (" state" ) != " open" :
6366 continue
64- portid = port .get (' portid' )
67+ portid = port .get (" portid" )
6568 if not portid :
6669 continue
6770 try :
0 commit comments