Search code examples
awksednmap

Extracting IP address and ports of NMAP scan in seperate lines


I do a nmap scan of a domain and want to output the IP address and all open ports in the form of:

127.0.0.1:22
127.0.0.1:80
127.0.0.1:443

I have the following bash script

nmap -vv -sV subdomain.domain.tld -oG - |  awk '/open/' | awk '{printf "%s:", $2;
  for (i=4;i<=NF;i++) {
    split($i,a,"/");
    if (a[2]=="open") printf ",%s",a[1];}
  print ""}' |
sed -e 's/,//' 

It outputs the following:

127.0.0.1:22,80,443

I can't get it to pass the value of the IP address into the for loop so I can output it per line. I feel like it just needs a little tweak to get the output I want.


Solution

  • You already have the value of $2, which you can use printing the value of the ip with : and the port.

    I think you can omit the pipe to sed at the end, and you can use a single pipe to awk starting with matching the pattern /open/ {

    nmap -vv -sV localhost -oG - | awk -v OFS=':' '
    /open/ {
      for (i=4;i<=NF;i++) {
        split($i,a,"/");
        if (a[2]=="open") print $2, a[1]
      }
    }'
    

    Output

    127.0.0.1:80
    127.0.0.1:443
    ...etc