How can you write your own simple port scanner using python3

In initial steps of a pentest, port scanning is one of the most important step you are going to perform. There are lot of tools already available out there to perform port scanning but in some cases tools don’t work. Knowing little bit programming is always an advantage for a hacker because sometimes tools fails and there are chances that you need to search a lot for a tool for your particular case while pentesting, you may find the required tool but this will eat up your time. Python language is all time favourite choice of hackers. So in this post we are going to see how we can write a simple port scanner(non-threaded) using python so that you can begin with learning python for pentesting.

Simple code shown above is just taking the positional(host) and optional arguments(ports) from command line using python library argparse. After parsing, a list is made containing hosts and ports to be scanned. In line 51 I have taken random ports as default ports in case user do not provide any ports, you can change them if you want.

This is another function which takes the list of hosts and ports you made in previous step as parameter. Then in line 27 host is resolved to get the IP address of the host and if our script unable to resolve the host then except section is triggered. Now from line 33 sockConnect(ip,port) function is called for each IP and port present in the list. Now let’s see what sockConnect function is doing.

For each IP and Port, the above shown function is called. This function is creating a socket connection using the IP and port passed to it and line 12 is triggered if no connection is established. After that random data is sent in line 15 in byte format and receiving the banner given as response by the server in result variable to print it on terminal. If for some reason something went wrong then except section is triggered.

Now your simple port scanner is ready and you can run it to scan a vulnerable machine. Let’s see what result is given on scanning some ports of metasploitable2 machine.

You can also make this script to run as a linux command, just make this script as executable using chmod command and move this script to /usr/bin. After this you can run your script from any location using terminal.

Get complete code from here:

Thanks for reading this post hope you liked it….



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ashutosh Verma

An avid learner in the field of information security. A self learner and a ctf player sometimes.