Custom Port Scanner using Python
Port scanning is part of the first phase of a penetration test and allows you to find all network entry points available on a target system.
Let’s start building Custom Port Scanner
To build Custom Port Scanner we are going to use following libraries
- Socket
- sys
Socket: This module provides access to the BSD socket interface. It is available on all modern Unix systems, Windows, MacOS, and probably additional platforms. To read more read official Python Document. Link
Sys : To parse command line arguments.
First Step is to take HOST Name from user via command line.
So for that we will check length of sys.argv . if we see user has not given Host name in command line arguments then we will give them error like this.
To accomplice this we will use if condition to check length of arguments.
If user has given valid arguments then we will go in else part. where we first take host_name in host variable and then we will call scan_ports function. which we will create later.
Now let’s create custome “scan_ports” function which takes host_name as arguments.
First thing we will do is to create socket() instance with two parameters.
AF_INET refers to the address family ipv4.
SOCK_STREAM means connection oriented TCP protocol.
Now let’s connect to host using socket.
Now here we are going to check top 1000 ports. So for that we will use for loop and we will call connect method each time.
If we are not able to connect to host with specific port then it will trow following error.
“[WinError 10061] No connection could be made because the target machine actively refused it”
So here we apply simple logic.We will use try and catch block.
If we are able to connect to host with specific port then we will say Port is open.
If we encounter any error then we will catch it via Except block. we will say Port is Closed.
So now let’s put all things together and our Custom Port Scanner is ready.
This is how we can create our simple port scanner.
You can get full source code from below link.
https://github.com/raj1997/Python-For-Pentester/tree/master/Port-Scanner
Still we need to add lot of things but we will add then later.
Note :Please do not scan any website without proper permissions from owner of website.