Sponsored by

Make Nmap list any number of its most common ports

Posted in Articles on January 3, 2023

Make Nmap list any number of its most common ports

After last week’s humongous cheatsheet, here’s a quick Nmap trick while I’m working on the next cheatsheet.

Long story short, I needed to get lists of Nmap’s 10, 20, 100, 200, etc, most common ports. Instead of relying on wordlists, I found this way to make Nmap itself give the answer.

List the X most common ports

TCP

nmap -oX - --top-ports <number-of-ports>

The trick here is to use XML output and send it to STDOUT with -oX -.

E.g.:

$ nmap -oX - --top-ports 30
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE nmaprun>
<?xml-stylesheet href="file:///usr/bin/../share/nmap/nmap.xsl" type="text/xsl"?>
<!-- Nmap 7.93 scan initiated Thu Dec 29 11:32:03 2022 as: nmap -oX - -&#45;top-ports 30 x -->
<nmaprun scanner="nmap" args="nmap -oX - -&#45;top-ports 30 x" start="1672309923" startstr="Thu Dec 29 11:32:03 2022" version="7.93" xmloutputversion="1.05">
<scaninfo type="connect" protocol="tcp" numservices="30" services="21-23,25,53,80-81,110-111,113,135,139,143,199,443,445,465,548,587,993,995,1025,1720,1723,3306,3389,5900,6001,8080,8888"/>
<verbose level="0"/>
<debugging level="0"/>
Failed to resolve "x".
WARNING: No targets were specified, so 0 hosts scanned.
<runstats><finished time="1672309923" timestr="Thu Dec 29 11:32:03 2022" summary="Nmap done at Thu Dec 29 11:32:03 2022; 0 IP addresses (0 hosts up) scanned in 0.07 seconds" elapsed="0.07" exit="success"/><hosts up="0" down="0" total="0"/>
</runstats>
</nmaprun>

UDP

Same for UDP (except that sudo is required):

sudo nmap -sU -oX - --top-ports <number-of-ports>

Make the output cleaner

TCP

To only display the list of ports:

nmap -oX - --top-ports <number-of-ports> 2>/dev/null | grep scaninfo | sed 's/.*services="//g' | sed 's/"\/>//g'

E.g.:

$ nmap -oX - --top-ports 15 2>/dev/null | grep scaninfo | sed 's/.*services="//g' | sed 's/"\/>//g'
21-23,25,53,80,110,135,139,143,443,445,3306,3389,8080

UDP

Same for UDP (with sudo):

sudo nmap -sU -oX - --top-ports <number-of-ports> 2>/dev/null | grep scaninfo | sed 's/.*services="//g' | sed 's/"\/>//g'

Simplify with Bash functions

There’s no need to remember all of this when we have Bash functions, right?

Add this to your ~/.bashrc file:

function list-nmap-ports-tcp {
    nmap -oX - --top-ports $1 2>/dev/null | grep scaninfo | sed 's/.*services="//g' | sed 's/"\/>//g'
}

function list-nmap-ports-udp {
    sudo nmap -sU -oX - --top-ports $1 2>/dev/null | grep scaninfo | sed 's/.*services="//g' | sed 's/"\/>//g'
}

Then source it to update your current shell:

source ~/.bashrc

Now forget all of the above and just use this to list common ports:

$ list-nmap-ports-udp 10
[sudo] password for janedoe:
53,67,123,135,137-138,161,445,631,1434

$ list-nmap-ports-tcp 10
21-23,25,80,110,139,443,445,3389
Top