Continuing on from the "Quick and dirty Python: masscan" diary, which implemented a simple port scanner in Python using masscan to detect web instances on TCP ports 80 or 443. Masscan is perfectly good as a blunt instrument to quickly find open TCP ports across large address spaces, but for fine details it is better to use a scanner like nmap that, while much slower, is able to probe the port to get a better idea of what is running.
First lets backtrack. Since the previous diary, I converted the masscan code to a function and created another function to parse the masscan results to return the list of IPs on which masscan detected open ports. The current script scan_web.py script is:
Running the script results in a list of IPs where either 80 or 443 were detected open by masscan.
Extending this script to pass the masscan output list to nmap is relatively easy as well. As somebody pointed out on a comment to the last diary, there are a lot of Python nmap modules and they all provide differing functionality. After messing with a few of them, as the comment stated, the libnmap module appears to be the most functional and easiest to use. libnmap does not implement nmap functionality, it needs nmap already installed on the device and interfaces with that version. I will not be going over nmap functionality in this diary. If you are not clear on the nmap command parameters you can find a quick tutorial in this older diary.
To implement the nmap scan will require two functions. One to run the scan, and one to parse the results.
The scanning function:
and the function to parse and output the scan result. This example is almost verbatim from the libnmap documentation.
The output from the finished script is:
In about 80 lines of python code. I have implemented a simple script that can quickly scan a large address space using the very quick masscan and then send the output to nmap to do detailed scanning of a single port. This script is the basic framework I use for dozens of scripts to scan an entire ASN looking for devices that may be at risk for the current vulnerability of the week.
The final version of the scan_web.py script is:
Caveat1: Never scan an IP range you don't have permission to scan. While port scanning is not illegal in most jurisdictions it is questionable ethically to scan things you don't own or have permission to scan.
Caveat2: I am not a professional Python programmer. My scripting gets the job done that I need it to do. I know there are many smart people out there who can write way better code than I can.
-- Rick Wanner MSISE - rwanner at isc dot sans dot edu - Twitter:namedeplume (Protected)
May 31st 2021
|Thread locked Subscribe||
May 31st 2021
1 year ago