Marcus
Marcus

Reputation: 9492

Parse Nmap result BASH

I'm writing a BASH script. From the command line I can call nmap and I want to extract the ip for a specific port.

$ nmap [ip]/24

Starting Nmap 6.47 ( http://nmap.org ) at 2015-02-26 01:59 PST
Nmap scan report for 192.168.56.1
Host is up (0.0012s latency).
Not shown: 500 closed ports, 499 filtered ports
PORT     STATE SERVICE
3689/tcp open  rendezvous

Nmap scan report for 192.168.56.101
Host is up (0.00042s latency).
Not shown: 998 closed ports
PORT   STATE SERVICE
21/tcp open  ftp
22/tcp open  ssh

I want the IP address for the port 21. In this example that would be 192.168.56.101. How do I extract that from this return and save it to a variable? Thanks

Upvotes: 1

Views: 4608

Answers (3)

bonsaiviking
bonsaiviking

Reputation: 6005

Nmap's normal output is human-readable, but can change from version to version. It is not designed to be machine-parseable. Nmap has 2 machine-parseable output formats that are a much better fit. First, XML output (using the -oX option) is the most complete format, containing as much or more information than the normal output. You can parse this with xmlstarlet or xmllint.

Another popular option for simple extraction of basic port scan information is the officially deprecated Grepable output format (-oG). This format is missing lots of the "more recent" features like NSE script output and traceroute info, but it is stable for port scan data. Here's how you could go about using this format:

nmap $target -oG - | awk '/ 21\/open\/tcp/{print $2}'

Upvotes: 1

hek2mgl
hek2mgl

Reputation: 158220

You can use xml output and parse the output using xmllint:

nmap -p 21 -oX - "$IP"/24 | xmllint --xpath '//port[@portid="21"]/state[@state="open"]/../../../address/@addr' -

Upvotes: 5

Some programmer dude
Some programmer dude

Reputation: 409442

Loop over each line in the output, and look the string "Nmap scan report for <your ip address>", then continue to loop over each line of the output until you either find the line "21/tcp open ftp" or you find an empty line or the end of the output.

The looping can be done with the Bash builtin commands read and while.

Upvotes: 0

Related Questions