Python Port Scanner

I was going through another lesson in a TCM ethical hacking course and learned a quick way to build a scanner using Python. I thought it would be beneficial to write it out and share my thought process behind this simple scanner.

Initial setup

First, we need to import sys. This will allow us to be able to pass arguments for the scanner as well as utilize basic functions like exiting the scanner.

The next thing we import is a socket. Sockets are needed to allow us to be able to establish connections with said hosts.

Finally, datetime will be used for us to have a nice display of the time started when scanning.

Building it out:

We can use an if statement partnered with “len” to specify that there is a second argument when running the scanner. The second argument is the typed-out host or IP. We also can add a variable for “target” which uses the socket module to translate hostnames to ipv4 addresses.

Otherwise, if there are no additional arguments the else portion is used which basically prints out statements indicating that there is a syntax.

We can then add a simple banner using print statements. This will be where we include the target variable as well as the datetime module.

We then utilize the try statement for our said ip address. Which is basically a for loop with conditions that would happen.

First, we specify that the variable port will go through a said range of 50 and 85 when attempting to connect. We create “S” as a variable for the socket.socket(socket.AF_INET, socket.SOCK_STREAM).

AF_INET is the ipv4 portion and SOCK_STREAM is the port. We set the default time out to 1 so that it does not try to continue scanning. An if statement is used to print out the port if the result is “0” which means an open port. Of course, we also use the same socket to then close the connection.

Finally, we include some exceptions.

If there is a keyboard interruption, like ctrl c. We can exit the scanner.

If there is an issue with resolving the hostname to an IP address. We have a print statement that addresses this.

Also, if the socket is unable to establish the connection we have a print statement for that as well.

For each exception. We use sys.exit() to cancel the connections.

Output

Final Thoughts

While this may not be the most polished port scanner, I believe it effectively demonstrates the proof of concept.

I am still continually learning about building tools like this, and it definitely gets my wheels spinning to explore ways of optimizing my workflow in future penetration tests and security assessments.