Create Simple Port Scanner in Kali Linux

Create Simple Port Scanner in Kali Linux

Your very own port scanner made all by yourself

Your very own port scanner made all by yourself

Your very own port scanner made all by yourself

Your very own port scanner made all by yourself

Client

Self

Services

Port Scanner

Industries

Tech

Date

Oct 1, 2023

Kali Linux is a popular distribution for penetration testing and ethical hacking, equipped with a wide range of tools for various security tasks, including port scanning. Some of the commonly used port scanning tools in Kali Linux include Nmap (Network Mapper), Netcat, Zenmap, Masscan, Unicornscan, Amap, Hping, Scapy, Sslscan, and Xprobe2. Port scanning is a vast field with numerous possibilities for improvement and exploration. Today, I will demonstrate how to create a simple port scanner from scratch, without any dependencies or complications. No strings attached, just pure genius. It's time to show your boss who's the real boss.

Kali Linux is a popular distribution for penetration testing and ethical hacking, equipped with a wide range of tools for various security tasks, including port scanning. Some of the commonly used port scanning tools in Kali Linux include Nmap (Network Mapper), Netcat, Zenmap, Masscan, Unicornscan, Amap, Hping, Scapy, Sslscan, and Xprobe2. Port scanning is a vast field with numerous possibilities for improvement and exploration. Today, I will demonstrate how to create a simple port scanner from scratch, without any dependencies or complications. No strings attached, just pure genius. It's time to show your boss who's the real boss.

Kali Linux is a popular distribution for penetration testing and ethical hacking, equipped with a wide range of tools for various security tasks, including port scanning. Some of the commonly used port scanning tools in Kali Linux include Nmap (Network Mapper), Netcat, Zenmap, Masscan, Unicornscan, Amap, Hping, Scapy, Sslscan, and Xprobe2. Port scanning is a vast field with numerous possibilities for improvement and exploration. Today, I will demonstrate how to create a simple port scanner from scratch, without any dependencies or complications. No strings attached, just pure genius. It's time to show your boss who's the real boss.

Let's cut to the point. Bellow is the code for building your very own port scanner.


#!/bin/python3

import sys
import socket
from datetime import datetime

#define our target
if len(sys.argv) ==2:
	target = socket.gethostbyname(sys.argv[1])
else:
	print("invalid amount of arguments.")
	print("Syntext: python3 scanner.py <ip>")
	
#Add a pretty Banner
print("-" * 50)
print ("Scanning target " + target)
print("Time started:"+str(datetime.now()))
print("-" * 50)

try:
	for port in range(50,800):
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		socket.setdefaulttimeout(1)
		result  =s.connect_ex((target,port))
		if result == 0:
			print(f"Port {port} is open")
		s.close()
	
except KeyboardInterrupt:
	print("\nExiting program.")
	sys.exit()
except socket.gaierror:
	print("Hostname could be resolved.")
	sys.exit()
except socket.error:
	print("Could not connect to server.")
	sys.exit()


Now, where the heck you use this code right? Don't worry, I got you!


  1. Open your kali machine

  2. Open Terminal

  3. Type mousepad scanner.py

  4. Copy and paste above code into it.

Let's cut to the point. Bellow is the code for building your very own port scanner.


#!/bin/python3

import sys
import socket
from datetime import datetime

#define our target
if len(sys.argv) ==2:
	target = socket.gethostbyname(sys.argv[1])
else:
	print("invalid amount of arguments.")
	print("Syntext: python3 scanner.py <ip>")
	
#Add a pretty Banner
print("-" * 50)
print ("Scanning target " + target)
print("Time started:"+str(datetime.now()))
print("-" * 50)

try:
	for port in range(50,800):
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		socket.setdefaulttimeout(1)
		result  =s.connect_ex((target,port))
		if result == 0:
			print(f"Port {port} is open")
		s.close()
	
except KeyboardInterrupt:
	print("\nExiting program.")
	sys.exit()
except socket.gaierror:
	print("Hostname could be resolved.")
	sys.exit()
except socket.error:
	print("Could not connect to server.")
	sys.exit()


Now, where the heck you use this code right? Don't worry, I got you!


  1. Open your kali machine

  2. Open Terminal

  3. Type mousepad scanner.py

  4. Copy and paste above code into it.

Dyamn Son! You just made your first ever port scanner! Wait, what's that? You're wondering how to use it? I got you homie!

Do dis 👇


  1. open up your terminal

  2. type 👉 python3 scanner.py [ip]

  3. replace [ip] with your ip desired address that you wanna scan.


💥BOOM! Self made port scanner in your boss's face! Ain't nobody is getting bullied now son!

Dyamn Son! You just made your first ever port scanner! Wait, what's that? You're wondering how to use it? I got you homie!

Do dis 👇


  1. open up your terminal

  2. type 👉 python3 scanner.py [ip]

  3. replace [ip] with your ip desired address that you wanna scan.


💥BOOM! Self made port scanner in your boss's face! Ain't nobody is getting bullied now son!

Arryt, arryt. Now, I know what you've thinking. Hey Akane, I know this code runs like melted butter on a pan, but what am I seeing here? Ain't nobody buying that we're cool if we can't explain sheet right? You asked for it!


So! Nerd Alert!


The code you is a simple custom port scanner written in Python 3. Let me describe each part of the code in detail:


  1. Import Statements:

    import sys
    import socket
    from datetime import datetime


    sys: This module provides access to some variables used or maintained by the interpreter and to functions that interact with the interpreter.

    socket: The socket module provides low-level network programming capabilities.

    datetime: The datetime module is used to work with dates and times.

  2. Target Definition:

    if len(sys.argv) == 2:
        target = socket.gethostbyname(sys.argv[1])
    else:
        print("Invalid number of arguments.")
        print("Syntax: python3 scanner.py <ip>")
        sys.exit()



    • This part of the code checks if the script is executed with the correct number of arguments (i.e., one argument, which is the target IP address).

    • If the correct number of arguments is provided, it retrieves the IP address of the target using socket.gethostbyname().

  3. Banner and Information Display:



    print("-" * 50)
    print("Scanning target " + target)
    print("Time started: " + str(datetime.now()))
    print("-" * 50)



    • These lines are used to display a banner with a horizontal line to separate information.

    • It shows the target IP address and the current date and time when the scan started.

  4. Port Scanning Loop:


    try:
        for port in range(50, 800):
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            socket.setdefaulttimeout(1)
            result = s.connect_ex((target, port))
            if result == 0:
                print(f"Port {port} is open")
            s.close()



    • This part of the code contains the main scanning logic.

    • It uses a for loop to iterate through a range of port numbers from 50 to 799.

    • For each port, it creates a socket (socket.socket) with IPv4 address family (socket.AF_INET) and TCP socket type (socket.SOCK_STREAM).

    • It sets a socket timeout of 1 second to avoid long hangs in case a port is unresponsive.

    • It attempts to establish a connection (s.connect_ex()) to the target IP address and port. If the result is 0, it means the port is open, and it prints a message indicating that the port is open.

    • Finally, it closes the socket.

  5. Exception Handling:

    except KeyboardInterrupt:
        print("\nExiting program.")
        sys.exit()
    except socket.gaierror:
        print("Hostname could not be resolved.")
        sys.exit()
    except socket.error:
        print("Could not connect to the server.")
        sys.exit()



    • The code includes exception handling to catch different types of errors that might occur during execution.

    • If the user interrupts the program (e.g., by pressing Ctrl+C), it gracefully exits the program.

    • If there is an issue with hostname resolution or a generic socket error, it displays an error message and exits.


This code provides a basic example of a port scanner that iterates through a range of ports on a target IP address and checks if they are open or closed. However, it's important to note that real-world port scanning should be performed responsibly and within legal boundaries, with proper authorization and consent. Unauthorized port scanning can have legal and ethical consequences.

Arryt, arryt. Now, I know what you've thinking. Hey Akane, I know this code runs like melted butter on a pan, but what am I seeing here? Ain't nobody buying that we're cool if we can't explain sheet right? You asked for it!


So! Nerd Alert!


The code you is a simple custom port scanner written in Python 3. Let me describe each part of the code in detail:


  1. Import Statements:

    import sys
    import socket
    from datetime import datetime


    sys: This module provides access to some variables used or maintained by the interpreter and to functions that interact with the interpreter.

    socket: The socket module provides low-level network programming capabilities.

    datetime: The datetime module is used to work with dates and times.

  2. Target Definition:

    if len(sys.argv) == 2:
        target = socket.gethostbyname(sys.argv[1])
    else:
        print("Invalid number of arguments.")
        print("Syntax: python3 scanner.py <ip>")
        sys.exit()



    • This part of the code checks if the script is executed with the correct number of arguments (i.e., one argument, which is the target IP address).

    • If the correct number of arguments is provided, it retrieves the IP address of the target using socket.gethostbyname().

  3. Banner and Information Display:



    print("-" * 50)
    print("Scanning target " + target)
    print("Time started: " + str(datetime.now()))
    print("-" * 50)



    • These lines are used to display a banner with a horizontal line to separate information.

    • It shows the target IP address and the current date and time when the scan started.

  4. Port Scanning Loop:


    try:
        for port in range(50, 800):
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            socket.setdefaulttimeout(1)
            result = s.connect_ex((target, port))
            if result == 0:
                print(f"Port {port} is open")
            s.close()



    • This part of the code contains the main scanning logic.

    • It uses a for loop to iterate through a range of port numbers from 50 to 799.

    • For each port, it creates a socket (socket.socket) with IPv4 address family (socket.AF_INET) and TCP socket type (socket.SOCK_STREAM).

    • It sets a socket timeout of 1 second to avoid long hangs in case a port is unresponsive.

    • It attempts to establish a connection (s.connect_ex()) to the target IP address and port. If the result is 0, it means the port is open, and it prints a message indicating that the port is open.

    • Finally, it closes the socket.

  5. Exception Handling:

    except KeyboardInterrupt:
        print("\nExiting program.")
        sys.exit()
    except socket.gaierror:
        print("Hostname could not be resolved.")
        sys.exit()
    except socket.error:
        print("Could not connect to the server.")
        sys.exit()



    • The code includes exception handling to catch different types of errors that might occur during execution.

    • If the user interrupts the program (e.g., by pressing Ctrl+C), it gracefully exits the program.

    • If there is an issue with hostname resolution or a generic socket error, it displays an error message and exits.


This code provides a basic example of a port scanner that iterates through a range of ports on a target IP address and checks if they are open or closed. However, it's important to note that real-world port scanning should be performed responsibly and within legal boundaries, with proper authorization and consent. Unauthorized port scanning can have legal and ethical consequences.

This port scanner was taught in TCM Security.

Let's talk

Connecting with our clients to create tailor-made solutions

We specialize in crafting exceptional digital experiences to help our clients achieve their business goals.

Framer template crafted with love by Akane Asahi

Let's talk

Connecting with our clients to create tailor-made solutions

We specialize in crafting exceptional digital experiences to help our clients achieve their business goals.

Framer template crafted with love by Akane Asahi

Let's talk

Connecting with our clients to create tailor-made solutions

We specialize in crafting exceptional digital experiences to help our clients achieve their business goals.

Framer template crafted with love by Akane Asahi