Search code examples
awknmap

Nmap output with IP and OUI vendor


Want to transform this nmap output:

Nmap scan report for 192.168.1.38
Host is up (0.0092s latency).
MAC Address: B8:78:2E:XX:XX:XX (Apple)
Nmap scan report for 192.168.1.39
Host is up (0.0092s latency).
MAC Address: 40:6C:8F:XX:XX:XX (Apple)
Nmap scan report for 192.168.1.201
Host is up (0.019s latency).
MAC Address: 3C:DF:A9:XX:XX:XX (Arris Group)
Nmap scan report for 192.168.1.36
Host is up.
Nmap done: 256 IP addresses (4 hosts up) scanned in 1.77 seconds

Into:

192.168.1.38 (Apple)
192.168.1.39 (Apple)
192.168.1.201 (Arris Group)

Note that the last IP 192.168.1.36 (scanner IP) is not included.

With: sudo nmap -n -sn 192.168.1.0/24 | awk '/Nmap scan report/{printf $5;printf " ";getline;getline;print $4;}' > scan-output.txt

I include the scanner IP and only the first word of the vendor.

192.168.1.38 (Apple)
192.168.1.39 (Apple)
192.168.1.201 (Arris
192.168.1.36 IP

Please help. Thank you in advance!


Solution

  • Using awk

    One-liner:

    awk '/^(Nmap scan|MAC Address)/{ORS=(f+=sub(/^.*(for|:..) /,""))%2?OFS:RS; print}END{printf "IP\n"}' infile
    

    Better Readable:

    awk '/^(Nmap scan|MAC Address)/{
                ORS=(f+=sub(/^.*(for|:..) /,""))%2?OFS:RS;
                print
          }
          END{
               printf "IP\n"
          }
         ' infile
    

    Test Results:

    $ cat infile
    Nmap scan report for 192.168.1.38
    Host is up (0.0092s latency).
    MAC Address: B8:78:2E:XX:XX:XX (Apple)
    Nmap scan report for 192.168.1.39
    Host is up (0.0092s latency).
    MAC Address: 40:6C:8F:XX:XX:XX (Apple)
    Nmap scan report for 192.168.1.201
    Host is up (0.019s latency).
    MAC Address: 3C:DF:A9:XX:XX:XX (Arris Group)
    Nmap scan report for 192.168.1.36
    Host is up.
    Nmap done: 256 IP addresses (4 hosts up) scanned in 1.77 seconds
    
    $ awk '/^(Nmap scan|MAC Address)/{ORS=(f+=sub(/^.*(for|:..) /,""))%2?OFS:RS; print}END{printf "IP\n"}' infile
    192.168.1.38 (Apple)
    192.168.1.39 (Apple)
    192.168.1.201 (Arris Group)
    192.168.1.36 IP
    

    --edit for comment--

    $ awk 'f==2{print s; f=s=""}/^(Nmap scan|MAC Address)/{sub(/^.*(for|:..) /,"");f++;s=(s?s OFS :"")$0}END{if(f==2)print s}' infile
    192.168.1.38 (Apple)
    192.168.1.39 (Apple)
    192.168.1.201 (Arris Group)