Converting Nmap XML to CSV

Nmap is a common tool used in the reconnaissance phase of a web application test. It is normally used to scan ports with a variety of options to help you customise the scan to exactly how you like it. For instance, do you want to do TCP or UDP? What TCP flags do you want to set? Is there a particular Nmap script that you would like to run, such as checking for Network Time Protocol (NTP) reflection, but on a non-default port? The list can be endless.

The Nmap output is easy to read, but not very easy to use in a programmatic way. This simple recipe will convert XML output from Nmap (through the use of the –oX flag when running an Nmap scan) and convert it to CSV output.

Getting ready

While this recipe is very simple in its implementation, you will need to install Python’s nmap module. You can do this by using pip or building it from the source files. You will also need XML output from an Nmap scan. You can get this from scanning a vulnerable virtual machine of your choice or a site that you have permission to run a scan on. You can use Nmap as it is or you can use Python’s nmap module to do this within a Python script.

How to do it…

Like I mentioned earlier, this recipe is very simple. This is mainly due to the fact that the nmap library has done most of the hard work for us.

Here’s the script that we are going to use for this task:

import sys
import os
import nmap

nm=nmap.Portscanner()
with open(“./nmap_output.xml”, “r”) as fd:
    content = fd.read()
    nm.analyse_nmap_xml_scan(content)
    print(nm.csv())

How it works…

So, after the importing of necessary modules, we have to initialize an Nmap’s Portscanner function. Although we won’t be doing any port scanning within this recipe, this is necessary to allow us to use the methods within the object:

nm=nmap.Portscanner()

Then, we have a with statement. What’s one of those? Previously, when you opened files in Python, you would have to remember to close it once you were finished. In this situation, the with statement will do that for you once all the code within it has been executed. It’s great if you don’t have a great memory and keep forgetting to close files in your code:

with open(“./nmap_output.xml”, “r”) as fd:

After the with statement, we read the contents of the file into a content variable (we could call this variable whatever we want, but why overcomplicate things?):

    content = fd.read()

Using the Portscanner object we created earlier, we can now analyze the contents with a method that will parse the XML output we have provided, which we can then print out as a CSV:

nm.analyse_nmap_xml_scan(content)
    print(nm.csv())
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.246.223