Parser(3pm)
π Nmap::Parser β parse nmap scan data with perl π
okay bestie, so this is Nmap::Parser, and no cap, it's the moment. it's a perl module, it lives in the User Contributed Perl Documentation section, and it is literally about to make your nmap scans make sense. π
β¨ SYNOPSIS β¨
here's the vibe, bestie β copy it, love it, live it:
use Nmap::Parser;
my $np = new Nmap::Parser;
$np->parsescan($nmap_path, $nmap_args, @ips);
#or
$np->parsefile($file_xml);
my $session = $np->get_session();
#a Nmap::Parser::Session object
my $host = $np->get_host($ip_addr);
#a Nmap::Parser::Host object
my $service = $host->tcp_service(80);
#a Nmap::Parser::Host::Service object
my $os = $host->os_sig();
#a Nmap::Parser::Host::OS object
#---------------------------------------
my $np2 = new Nmap::Parser;
$np2->callback(\&my_callback);
$np2->parsefile($file_xml);
#or
$np2->parsescan($nmap_path, $nmap_args, @ips);
sub my_callback {
my $host = shift;
#Nmap::Parser::Host object
#.. see documentation for all methods ...
}
and for the full listing of methods, you gotta go peep the documentation that matches each object. you can also visit the website <https://github.com/modernistik/Nmap-Parser> for extra installation instructions. iykyk. π¦
πΈ DESCRIPTION πΈ
so basically this module implements an interface to all the info chilling inside an nmap scan. how? by parsing the xml scan data that nmap generates, periodt. this means literally anyone who uses nmap can speedrun creating fast and robust security scripts that take full advantage of nmap's powerful port scanning abilities. it's giving main character energy fr. π
the latest version of this module can be found on here <https://github.com/modernistik/Nmap-Parser> β go get it.
π«Ά OVERVIEW π«Ά
this module has an internal framework to make retrieving the info you actually want from a scan super easy. every nmap scan is built on two main sections of informations: the scan session, and the scan information of all hosts. the session info gets stored as a Nmap::Parser::Session object, and that object has its own methods to pull out the info you want. same deal for any hosts that got scanned, via the Nmap::Parser::Host object. π
under Nmap::Parser::Host there are two sub objects. one is the Nmap::Parser::Host::Service object, which you use to get info about a given service running on a given port. the second is the Nmap::Parser::Host::OS object, which holds the operating system signature information (OS guessed names, classes, osfamily..etc). look at this little family tree:
Nmap::Parser -- Core parser
|
+--Nmap::Parser::Session -- Nmap scan session information
|
+--Nmap::Parser::Host -- General host information
| |
| |-Nmap::Parser::Host::Service -- Port service information
| |
| |-Nmap::Parser::Host::OS -- Operating system signature information
π METHODS π
π« Nmap::Parser π«
the main idea behind the core module is: you first parse the information, and then you extract data. so the way that this works β all parse*() methods should be executed before any get_*() methods. no skipping the line, bestie. π€
parse($string)/parse($filehandle)β parses the nmap scan information in$string. note that this is usually only used if you have the whole xml scan information sitting in$string, or if you're piping the scan information. πparsefile($xml_file)β parses the nmap scan data in$xml_file. this file can be generated from an nmap scan by using the'-oX filename.xml'option with nmap. if you get an error or your program dies due to parsing, please check that the xml information is compliant. and heads up: the file is closed no matter how"parsefile()"returns. πparsescan($nmap,$args,@ips)β this method runs an nmap scan where$nmapis the path to the nmap executable or binary,$argsare the nmap command line parameters, and@ipsare the list of IP addresses to scan.parsescan()will automagically run the nmap scan and parse the information. iconic behavior honestly.
if you wish to save the xml output from parsescan(), you must call cache_scan() method BEFORE you start the parsescan() process. this is done to conserve memory while parsing. cache_scan() will let Nmap::Parser know to save the output before parsing the xml, since Nmap::Parser purges everything that has been parsed by the script to conserve memory and increase speed. β‘
see section EXAMPLES for a short tutorial.
Note: You cannot have one of the nmap options to be'-oX','-oN'or'-oG'. Your program will die if you try and pass any of these options because it decides the type of output nmap will generate. π The IP addresses can be nmap-formatted addresses see nmap(1)
if you get an error or your program dies due to parsing, please check that the xml information is compliant. if you are using parsescan() or an open filehandle, make sure that the nmap scan that you are performing is successful in returning xml information. (sometimes using loopback addresses causes nmap to fail). π
cache_scan($filename)β this function allows you to save the output of aparsescan()(or nmap scan) to the disk.$filenameis the name of the file you wish to save the nmap scan information to. it defaults tonmap-parser-cache.xml. it returns the name of the file to be used as the cache. π
#Must be called before parsescan().
$np->cache_scan($filename); #output set to nmap-parser-cache.xml
#.. do other stuff to prepare for parsescan(), ex. setup callbacks
$np->parsescan('/usr/bin/nmap',$args,@IPS);
purge()β cleans the xml scan data from memory. this is useful if you have a program where you are parsing lots of nmap scan data files with persistent variables. lowkey a lifesaver. π§callback(\&code_ref)β sets the parsing mode to be done using the callback function. it takes the parameter of a code reference or a reference to a function. if no code reference is given, it resets the mode to normal (no callback). π
$np->callback(\&my_function); #sets callback, my_function() will be called
$np->callback(); #resets it, no callback function called. Back to normal.
get_session()β obtains theNmap::Parser::Sessionobject which contains the session scan information. πget_host($ip_addr)β obtains theNmap::Parser::Hostobject for the given$ip_addr. π¦del_host($ip_addr)β deletes the storedNmap::Parser::Hostobject whose IP is$ip_addr. bye bestie πall_hosts()/all_hosts($status)β returns an array of all theNmap::Parser::Hostobjects for the scan. if the optional status is given, it will only return those hosts that match that status. the status can be any of the following:"(up|down|unknown|skipped)"β¨get_ips()/get_ips($status)β returns the list of IP addresses that were scanned in this nmap session. they are sorted usingaddr_sort. if the optional status is given, it will only return those IP addresses that match that status. the status can be any of the following:"(up|down|unknown|skipped)"πaddr_sort(@ips)β this function takes a list of IP addresses and returns the correctly sorted version of the list. it's giving organized. π
π Nmap::Parser::Session π
this object contains the scan session information of the nmap scan. it's the whole vibe of the session, if you will. π
finish_time()β returns the numeric time that the nmap scan finished. β°nmap_version()β returns the version of nmap used for the scan. π«numservices()/numservices($type)β ifnumservicesis called without argument, it returns the total number of services that were scanned for all types. if$typeis given, it returns the number of services for that given scan type. seescan_types()for more info. π₯scan_args()β returns a string which contains the nmap executed command line used to run the scan. β¨scan_type_proto($type)β returns the protocol type of the given scan type (provided by$type). seescan_types()for more info. π¦scan_types()β returns the list of scan types that were performed. it can be any of the following:"(syn|ack|bounce|connect|null|xmas|window|maimon|fin|udp|ipproto)". πstart_str()β returns the human readable format of the start time. πΈstart_time()β returns the numeric form of the time the nmap scan started. β±οΈtime_str()β returns the human readable format of the finish time. π«xml_version()β returns the version of nmap xml file. πprescripts()/prescripts($name)β a basic call toprescripts()returns a list of the names of the NSE scripts run in the pre-scanning phase. if$nameis given, it returns the text output of the a reference to a hash with"output"and"contents"keys for the script with that name, or undef if that script was not run. the value of the"output"key is the text output of the script. the value of the"contents"key is a data structure based on the XML output of the NSE script. πpostscripts()/postscripts($name)β a basic call topostscripts()returns a list of the names of the NSE scripts run in the post-scaning phase. if$nameis given, it returns the text output of the a reference to a hash with"output"and"contents"keys for the script with that name, or undef if that script was not run. the value of the"output"key is the text output of the script. the value of the"contents"key is a data structure based on the XML output of the NSE script. π
π Nmap::Parser::Host π
this object represents the information collected from a scanned host. it's literally the whole host, bestie. π
status()β returns the state of the host. it is usually one of these"(up|down|unknown|skipped)". π«Άaddr()β returns the main IP address of the host. this is usually the IPv4 address. if there is no IPv4 address, the IPv6 is returned (hopefully there is one). πaddrtype()β returns the address type of the address given byaddr(). πall_hostnames()β returns a list of all hostnames found for the given host. π¦extraports_count()β returns the number of extraports found. β¨extraports_state()β returns the state of all the extraports found. π₯hostname()/hostname($index)β as a basic call,hostname()returns the first hostname obtained for the given host. if there exists more than one hostname, you can provide a number, which is used as the location in the array. the index starts at 0; π
#in the case that there are only 2 hostnames
hostname() eq hostname(0);
hostname(1); #second hostname found
hostname(400) eq hostname(1) #nothing at 400; return the name at the last index
ipv4_addr()β explicitly return the IPv4 address. πΈipv6_addr()β explicitly return the IPv6 address. πmac_addr()β explicitly return the MAC address. π
mac_vendor()β Returns the vendor information of the MAC. It's giving hardware detective energy πdistance()β Returns the distance (in hops) of the target machine from the machine that performed the scan. How far did we travel? πtrace_error()β Returns a true value (usually a meaningful error message) if the traceroute was performed but could not reach the destination. In this case"all_trace_hops()"contains only the part of the path that could be determined. So like, it tried but couldn't fully slay the route πall_trace_hops()β Returns an array of Nmap::Parser::Host::TraceHop objects representing the path to the target host. This array may be empty if Nmap did not perform the traceroute for some reason (same network, for example). Some hops may be missing if Nmap could not figure out information about them. In this case there is a gap between the"ttl()"values of consecutive returned hops. See also"trace_error()". The way that traceroute hops are literally the main characters of the network journey πtrace_proto()β Returns the name of the protocol used to perform the traceroute. Protocol tea βtrace_port()β Returns the port used to perform the traceroute. Which port? That port πos_sig()β Returns an Nmap::Parser::Host::OS object that can be used to obtain all the Operating System signature (fingerprint) information. See Nmap::Parser::Host::OS for more details.
$os = $host->os_sig;
$os->name;
$os->osfamily;
Obsessed with getting that OS fingerprint π§
tcpsequence_class(),tcpsequence_index(),tcpsequence_values()β Returns the class, index and values information respectively of the tcp sequence. TCP sequence lore β¨ipidsequence_class(),ipidsequence_values()β Returns the class and values information respectively of the ipid sequence. IPID sequence vibes π¦tcptssequence_class(),tcptssequence_values()β Returns the class and values information respectively of the tcpts sequence. TCPTS sequence energy πΈuptime_lastboot()β Returns the human readable format of the timestamp of when the host had last rebooted. When did it last wake up? β°uptime_seconds()β Returns the number of seconds that have passed since the host's last boot from when the scan was performed. Uptime in seconds, periodt β±οΈhostscripts(),hostscripts($name)β A basic call tohostscripts()returns a list of the names of the host scripts run. If$nameis given, it returns a reference to a hash with"output"and"contents"keys for the script with that name, or undef if that script was not run. The value of the"output"key is the text output of the script. The value of the"contents"key is a data structure based on the XML output of the NSE script. Scripts slay πtcp_ports(),udp_ports()β Returns the sorted list of TCP|UDP ports respectively that were scanned on this host. Optionally a string argument can be given to these functions to filter the list.
$host->tcp_ports('open') #returns all only 'open' ports (even 'open|filtered')
$host->udp_ports('open|filtered'); #matches exactly ports with 'open|filtered'
Note that if a port state is set to'open|filtered'(or any combination), it will be counted as an'open'port as well as a'filtered'one. So it's like, both? Yes bestie, both π
tcp_port_count(),udp_port_count()β Returns the total of TCP|UDP ports scanned respectively. Counting them all π’tcp_port_state_ttl()β Returns the'reason_ttl'value present in nmap xml result. The TTL reason, iykyk βtcp_del_ports($portid, [$portid, ...]),udp_del_ports($portid, [ $portid, ...])β Deletes the current$portidfrom the list of ports for given protocol. Bye bye port πtcp_port_state($portid),udp_port_state($portid)β Returns the state of the given port, provided by the port number in$portid. What's the tea on this port? βtcp_open_ports(),udp_open_ports()β Returns the list of open TCP|UDP ports respectively. Note that if a port state is for example,'open|filtered', it will appear on this list as well. Open ports are the main characters πtcp_filtered_ports(),udp_filtered_ports()β Returns the list of filtered TCP|UDP ports respectively. Note that if a port state is for example,'open|filtered', it will appear on this list as well. Filtered ports, they're mysterious πtcp_closed_ports(),udp_closed_ports()β Returns the list of closed TCP|UDP ports respectively. Note that if a port state is for example,'closed|filtered', it will appear on this list as well. Closed ports, not today πtcp_service($portid),udp_service($portid)β Returns the Nmap::Parser::Host::Service object of a given service running on port, provided by$portid. See Nmap::Parser::Host::Service for more info.
$svc = $host->tcp_service(80);
$svc->name;
$svc->proto;
Service object? Slay π
Nmap::Parser::Host::Service π
This object represents the service running on a given port in a given host. This object is obtained by using the tcp_service($portid) or udp_service($portid) method from the Nmap::Parser::Host object. If a portid is given that does not exist on the given host, these functions will still return an object (so your script doesn't die). Its good to use tcp_ports() or udp_ports() to see what ports were collected. So like, no crash, just vibes π«Ά
confidence()β Returns the confidence level in service detection. How sure are we? π―extrainfo()β Returns any additional information nmap knows about the service. Extra tea βmethod()β Returns the detection method. How did we find it? πname()β Returns the service name. Name drop πowner()β Returns the process owner of the given service. (If available) Who runs this? πport()β Returns the port number where the service is running on. Port number, periodt π’product()β Returns the product information of the service. What product is this? ποΈproto()β Returns the protocol type of the service. Protocol vibes πrpcnum()β Returns the RPC number. RPC number, iykyk βtunnel()β Returns the tunnel value. (If available) Tunnel vision πfingerprint()β Returns the service fingerprint. (If available) Fingerprint, unique like you π§version()β Returns the version of the given product of the running service. Version check βscripts(),scripts($name)β A basic call toscripts()returns a list of the names of the NSE scripts run for this port. If$nameis given, it returns a reference to a hash with"output"and"contents"keys for the script with that name, or undef if that script was not run. The value of the"output"key is the text output of the script. The value of the"contents"key is a data structure based on the XML output of the NSE script. Scripts for days π
Nmap::Parser::Host::OS π
This object represents the Operating System signature (fingerprint) information of the given host. This object is obtained from an Nmap::Parser::Host object using the "os_sig()" method. One important thing to note is that the order of OS names and classes are sorted by DECREASING ACCURACY. This is more important than alphabetical ordering. Therefore, a basic call to any of these functions will return the record with the highest accuracy. (Which is probably the one you want anyways). So like, most accurate first, no cap π₯
all_names()β Returns the list of all the guessed OS names for the given host. All the names, all the guesses πclass_accuracy(),class_accuracy($index)β A basic call toclass_accuracy()returns the osclass accuracy of the first record. If$indexis given, it returns the osclass accuracy for the given record. The index starts at 0. Accuracy check π―class_count()β Returns the total number of OS class records obtained from the nmap scan. Count them all π’name(),name($index),names(),names($index)β A basic call toname()returns the OS name of the first record which is the name with the highest accuracy. If$indexis given, it returns the name for the given record. The index starts at 0. Name game strong πͺname_accuracy(),name_accuracy($index)β A basic call toname_accuracy()returns the OS name accuracy of the first record. If$indexis given, it returns the name for the given record. The index starts at 0. Accuracy of the name, got it? βname_count()β Returns the total number of OS names (records) for the given host. How many names? π’osfamily(),osfamily($index)β A basic call toosfamily()returns the OS family information of the first record. If$indexis given, it returns the OS family information for the given record. The index starts at 0. Family matters π¨βπ©βπ§βπ¦osgen(),osgen($index)β A basic call toosgen()returns the OS generation information of the first record. If$indexis given, it returns the OS generation information for the given record. The index starts at 0. Generation info, iconic πportused_closed()β Returns the closed port number used to help identify the OS signatures. This might not be available for all hosts. Closed port used? Interesting π΅οΈportused_open()β Returns the open port number used to help identify the OS signatures. This might not be available for all hosts. Open port used? Also interesting π΅οΈos_fingerprint()β Returns the OS fingerprint used to help identify the OS signatures. This might not be available for all hosts. The fingerprint, the signature ποΈtype(),type($index)β A basic call totype()returns the OS type information of the first record. If$indexis given, it returns the OS type information for the given record. The index starts at 0. Type check βvendor(),vendor($index)β A basic call tovendor()returns the OS vendor information of the first record. If$indexis given, it returns the OS vendor information for the given record. The index starts at 0. Vendor vibes π·οΈ
Nmap::Parser::Host::TraceHop π¦
This object represents a router on the IP path towards the destination or the destination itself. This is similar to what the "traceroute" command outputs. Nmap::Parser::Host::TraceHop objects are obtained through the "all_trace_hops()" and "trace_hop()" Nmap::Parser::Host methods. Each hop is a little milestone on the network journey π£οΈ
ttl()β The Time To Live is the network distance of this hop. TTL, the distance π«rtt()β The Round Trip Time is roughly equivalent to the"ping"time towards this hop. It is not always available (in which case it will be undef). RTT, ping time vibes πipaddr()β The known IP address of this hop. IP address, got it πhost()β The host name of this hop, if known. Host name, if we know it π
πΈ EXAMPLES πΈ
ngl bestie, some of us just learn better from examples, and honestly? Same. So here are a couple of examples to help you build custom security audit tools using some of the nice features of the Nmap::Parser module. Hopefully this can double as a tutorial. More tutorials (articles) can be found at <https://github.com/modernistik/Nmap-Parser>.
β‘ Real-Time Scanning β‘
You can run a nmap scan and have the parser parse the information automagically. The only constraint? You cannot use -oX, -oN, or -oG as one of your arguments for nmap command line parameters passed to parsescan(). That's the one rule, periodt.
use Nmap::Parser;
my $np = new Nmap::Parser;
my @hosts = @ARGV; #get hosts from cmd line
#runs the nmap command with hosts and parses it automagically
$np->parsescan('/usr/bin/nmap','-sS O -p 1-1023',@hosts);
for my $host ($np->all_hosts()){
print $host->hostname."\n";
#do mor stuff...
}
If you would like to run the scan using parsescan() but also save the scan xml output, you can use cache_scan(). You must call cache_scan() BEFORE you initiate the parsescan() method. Order matters, bestie, don't skip it π
use Nmap::Parser;
my $np = new Nmap::Parser;
#telling np to save output
$np->cache_scan('nmap.localhost.xml');
$np->parsescan('/usr/bin/nmap','-F','localhost');
#do other stuff...
π Callbacks π
This is probably the easiest way to write a script using Nmap::Parser, if you don't need the general scan session information. Here's the tea: during the parsing process, the parser will obtain information of every host. The callback function (in this case 'booyah()') is called after the parsing of every host (sequentially). When the callback returns, the parser will delete all information of the host it had sent to the callback. This callback function is called for every single host that the parser encounters. And the callback function must be setup before parsing π
use Nmap::Parser;
my $np = new Nmap::Parser;
$np->callback( \&booyah );
$np->parsefile('nmap_results.xml');
# or use parsescan()
sub booyah {
my $host = shift; #Nmap::Parser::Host object, just parsed
print 'IP: ',$host->addr,"\n";
# ... do more stuff with $host ...
#when it returns, host object will be deleted from memory
#(good for processing VERY LARGE files or scans)
}
π Multiple Instances - ("no less 'of'; my $self") π
Using multiple instances of Nmap::Parser is extremely useful in helping audit/monitor the network Policy (ohh noo! its that 'P' word!). In this example, we have a set of hosts that had been scanned previously for tcp services where the image was saved in base_image.xml. We now will scan the same hosts, and compare if any new tcp have been open since then (good way to look for suspicious new services). Easy security Compliance detection. (ooh noo! The 'C' word too!).
use Nmap::Parser;
use vars qw($nmap_exe $nmap_args @ips);
my $base = new Nmap::Parser;
my $curr = new Nmap::Parser;
$base->parsefile('base_image.xml'); #load previous state
$curr->parsescan($nmap_exe, $nmap_args, @ips); #scan current hosts
for my $ip ($curr->get_ips )
{
#assume that IPs in base == IPs in curr scan
my $ip_base = $base->get_host($ip);
my $ip_curr = $curr->get_host($ip);
my %port = ();
#find ports that are open that were not open before
#by finding the difference in port lists
my @diff = grep { $port{$_} < 2}
(map {$port{$_}++; $_}
( $ip_curr->tcp_open_ports , $ip_base->tcp_open_ports ));
print "$ip has these new ports open: ".join(',',@diff) if(scalar @diff);
for (@diff){print "$_ seems to be ",$ip_curr->tcp_service($_)->name,"\n";}
}
π¬ SUPPORT π¬
π£οΈ Discussion Forum
If you have questions about how to use the module, or any of its features, you can post messages to the Nmap::Parser module forum on CPAN::Forum. <https://github.com/modernistik/Nmap-Parser/issues>
π Bug Reports, Enhancements, Merge Requests
Please submit any bugs or feature requests to: <https://github.com/modernistik/Nmap-Parser/issues>
Please make sure that you submit the xml-output file of the scan which you are having trouble with. This can be done by running your scan with the -oX filename.xml nmap switch. Please remove any important IP addresses for security reasons. It saves time in reproducing issues. (Be a considerate bestie, fr fr π)
π SEE ALSO π
nmap,XML::Twig
The Nmap::Parser page can be found at: <https://github.com/modernistik/Nmap-Parser>. It contains the latest developments on the module. The nmap security scanner homepage can be found at: <http://www.insecure.org/nmap/>.
π«Ά AUTHORS π«Ά
Origiinal author, Anthony Persaud <https://www.modernistik.com>. However, special thanks to: Daniel Miller <https://github.com/bonsaiviking> and Robin Bowes <http://robinbowes.com>. Please see Changes.md file for a list of other great contributors. Shoutout to everyone who ever pushed a commit, y'all are the real ones π
π COPYRIGHT π
Copyright (c) <2003-2017> <Anthony Persaud> <https://www.modernistik.com>
MIT License
okay so this next bit is the legal tea and I'm not touching a single word of it, because lawyers are the one audience you do not improvise for π«£ verbatim, exactly as written:
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
And that's the whole page, bestie!! This one came from perl v5.36.0, dated 2022-11-20, and it lives in section 3pm as Parser(3pm). Go scan something responsibly, protect those IPs, and remember: cache before you parse π
β¨π¦
π¦ where this page comes from
- debian bookworm: libnmap-parser-perl 1.37-2 Β· MIT
- debian trixie: libnmap-parser-perl 1.37-2 Β· MIT
- ubuntu noble: libnmap-parser-perl 1.37-2 Β· MIT
- ubuntu resolute: libnmap-parser-perl 1.37-2 Β· MIT
- ubuntu stonking: libnmap-parser-perl 1.37-2 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms