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.

Raj Upadhyay
3 min readAug 26, 2020

Let’s start building Custom Port Scanner

To build Custom Port Scanner we are going to use following libraries

  1. Socket
  2. sys
library

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.

final Output

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.

error msg

To accomplice this we will use if condition to check length of arguments.

Error Check for Input

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.

valid input

Now let’s create custome “scan_ports” function which takes host_name as arguments.

scan_ports function

First thing we will do is to create socket() instance with two parameters.

socket instance

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.

for loop to connect host

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”

port close error

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.

--

--

Raj Upadhyay
Raj Upadhyay

Written by Raj Upadhyay

DFIR Consultant || #LoveToPlayCTF #infosec #cybersecurity #4n6

No responses yet