Another great tool to learn how to make is a port scanner. These tools can be very useful to be able to identify opened ports on your hosts or firewalls that are not meant to be open. Building a port scanner can be very simple but allows for other features to be added. Today we will be building a simple port scanner in 20 lines of code. Lets get started!
Building the Tool
First we will need to import a few standard libraries to help us out
The socket library is a low level networking interface library that allows us to create network connections within our script. The argparse library is used to interpret arguments passed to our script. The sys library allows us to interact with our system. Finally, the datetime library allows us to get the time within our script.
Now lets start building the actual tool!
First we are going to create an ArgumentParser object and get the host IP address that will need to be passed to our script.
Next we are going to get the current time. This will be useful later in the script.
Now we are going to create the bulk of our script in this try/except block. First we will create a for loop that will iterate through a range of the most common ports used in networking, from 1 to 1024. Within our for loop we will create a socket, try to connect to the IP address provided over the port, and if the result returns a zero then we connected successfully and can print out that the port is open. Finally we close the socket and do it all over again for the next port.
We also added an except statement so if someone passes Ctrl+C while the script is running it will close silently and not produce an error.
Once the for loop has completed and all the ports have been scanned, we will get the time and print out how long the script took to run.
Here is our completed script!
And were done! Now lets test it out our port scan
$ portscan.py "18.104.22.168"
Port: 25 Open
Port: 53 Open
Port: 110 Open
Port: 119 Open
Port: 143 Open
Port: 443 Open
Port: 465 Open
Port: 563 Open
Port: 587 Open
Port: 853 Open
Port: 993 Open
Port: 995 Open
Scanning completed in: 0:16:52.479625
We now have a functional script that allows us to scan ports for any host we provide it. However it took 16 minutes to scan one host! Unfortunately this script does take a long time to run since we are scanning the host synchronously. This means that we need to wait for a response from the host or a timeout before we are able to send a request to the host over another port. This can be resolved by using threading to send the requests asynchronously but that is out of the scope of this tutorial. If you have any questions or would like me to write about threading in Python leave a comment below!
Thanks for reading!