Sunday, October 28, 2012

Some More Python & Nmap

As an exercise, I decided to write a Python script that performed an Nmap scan on my home network and showed the difference between scans.

I found that Nmap has the option to output to XML format and that a style-sheet is included with Nmap to allow for easier viewing.

ndiff, which, comes with Nmap is used to show the differences between Nmap scans like the Unix/Linux diff command does with files.  It has the ability to output to XML format, but a style-sheet isn't included and Nmap's style-sheet doesn't format ndiff's XML output correctly.

yandiff is an improvement to ndiff that adds more functionality, including a XML style-sheet.

The script I wrote is a little rough, but it works in the following way;
1) Run nmap with the "-A" and "-PN" arguments against the specified network and output to XML format with the date timestamped in the file name.
2) Use yandiff to compare the current week's scan with the previous week's scan and output the result to XML format with the date timestamped in the file name.
3) Use xsltproc to convert the Nmap scan results and the yandiff results to HTML

I then scheduled a cron job to run the script weekly.

Update:
I wrote another version of the script that uses os.fork() and the os.exec*() family of functions.  I did this to make the script a little cleaner and also to learn about process management.  The results are the same as the previous script, just done a little differently.

I learned an interesting lesson on how global variables and forking to create new processes work.

The code can be found here.

Below are samples of the results: