service ports discover with nmap

Starting Nmap 7.91 ( https://nmap.org ) at 2020-12-07 15:20 +08
 Nmap scan report for 10.10.10.161
 Host is up (0.0087s latency).
 Not shown: 65511 closed ports
 PORT      STATE SERVICE
 53/tcp    open  domain
 88/tcp    open  kerberos-sec
 135/tcp   open  msrpc
 139/tcp   open  netbios-ssn
 389/tcp   open  ldap
 445/tcp   open  microsoft-ds
 464/tcp   open  kpasswd5
 593/tcp   open  http-rpc-epmap
 636/tcp   open  ldapssl
 3268/tcp  open  globalcatLDAP
 3269/tcp  open  globalcatLDAPssl
 5985/tcp  open  wsman
 9389/tcp  open  adws
 47001/tcp open  winrm
 49664/tcp open  unknown
 49665/tcp open  unknown
 49666/tcp open  unknown
 49667/tcp open  unknown
 49671/tcp open  unknown
 49676/tcp open  unknown
 49677/tcp open  unknown
 49684/tcp open  unknown
 49706/tcp open  unknown
 49942/tcp open  unknown

I want to retrieve only the port numbers and arrange them into a series of numbers separated by commas.

I can first retrieve rows that have port numbers by using grep ^[0-9] this captures all rows that have number at the start of each row.

Then I can use cut in order to get only numbers of each row by using cut -d '/' -f 1

The cut command “cut” each row with a delimiter “/”, and only get the first field which is -f 1

To make each row a single line row, I use tr "\n" "," or tr '\n', ',' (notice the double and single quotes) which changes all new line to commas.

At the end of the row I will have a comma, to remove the comma at the end of file I use sed "s/,$//"

The format of sed command is sed "s/{pattern}/{replace_pattern}/" so comma is “removed” at the end of the file.

To combine all these:

#!/bin/bash

if [ $# -eq 0 ]; then
        echo "Usage $0 <target_ip> <outfile_name>"
else
        ip=$1
        ports=$(nmap -p- --min-rate=1000 -T4 $ip | grep ^[0-9] | cut -d '/' -f 1 | tr '\n', ',' | sed 's/,$//')
        nmap -sC -sV -p $ports $ip -vvv -oN $2
fi

Leave a comment