Port Scanning With Python

Port Scanning With Python

Hey there 👋, we are going to learn about port-scanning today and we shall also implement a simple python script using the python socket library.

I love cyber security and I actually find it easy given Python is extensively used nowadays because of its simplicity and easy implementation.

🔸 Wait, What Is Port Scanning?

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.

image.png Port scanning is a method attackers use to scope out their target environment by sending packets to specific ports on a host and using the responses to find vulnerabilities and understand which services, and service versions, are running on a host.

🔸How do you protect against port scanning 👀?

Install a Firewall: A firewall can help prevent unauthorized access to your private network. It controls the ports that are exposed and their visibility.

Some firewalls can also detect a port scan in progress and shut them down.

🔸Techniques 🛠

One of the more common and popular port-scanning techniques is the TCP half-open port scan, sometimes referred to as an SYN scan. It's a fast and sneaky scan that tries to find potential open ports on the target computer.

SYN packets request a response from a computer, and an ACK packet is a response.

Read more about the TCP handshake here

🔸Python Implementation 🚀🚀

There are 65,535 possible port numbers, although not all are in common use. Some of the most commonly used ports, along with their associated networking protocol, are Ports 20 and 21: File Transfer Protocol (FTP).


🔹Script Dependencies

📌 pyfiglet -Takes ASCII text and renders it in ASCII art fonts.
📌 sys -It lets us access system-specific parameters and functions.
📌 socket -Building full-fledged network applications including client and server programs.
📌 datetime -Supplies classes to work with date and time.

So let us begin by importing them

import pyfiglet
import sys
import socket
from datetime import datetime

You only have to pip install pyfiglet from the list above since others come with the standard lib as of Python 3 and above

# So let's print our banner
ascii_banner = pyfiglet.figlet_format("PORT SCANNER")

🔹 Defining a target:

if len(sys.argv) == 2:

    # translate hostname to IPv4
    target = socket.gethostbyname(sys.argv[1])
    print("Invalid amount of Argument")

So from the above command, it means that when running this script, we need to pass in two arguments in the command line. You can add print(sys.argv) to see what I am referring to;

The second argument (sys.argv[1]) being our target machine, can be a remote or local IP address.

🔹 Adding Banner & CLI Beautification

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

🔹 Port-Scanning Code

So let's try to port scan the target now; we use a try block to catch errors we might interface along the way:


    # will scan ports between 1 to 65,535
    for port in range(1,65535):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        # returns an error indicator
        result = s.connect_ex((target,port))
        if result ==0:
            print("Port {} is open".format(port))

# When you terminate the program
except KeyboardInterrupt:
        print("\n Exiting Program !!!!")

# For an invalid hostname
except socket.gaierror:
        print("\n Hostname Could Not Be Resolved !!!!")

except socket.error:
        print("\ Server not responding !!!!")

🔹 Code Explanation

From the code above, AF_INET is the Internet address family for IPv4.

SOCK_STREAM is the socket type for TCP, the protocol that will be used to transport our messages in the network and they are both passed when instantiating a socket object.

The most common cause of a socket error defined in the last line above is a firewall or antivirus program blocking the socket. On the side of the user's computer, socket error problems generally come from the Internet connection.

image.png Now if you want to scan your own computer(local host). You can get the target from running ipconfig/all and checking on IPv4 address. Alternatively, you can pass as the IP address.

🔹 Why 127.0. 0.0 ??

Network 127.0. 0.0 is reserved for IP traffic local to your host. Usually, address 127.0. 0.1 will be assigned to a special interface on your host, the loopback interface, which acts like a closed circuit.

The address 127.0. 0.1 is the standard address for IPv4 loopback traffic;

image.png After running the script above with let's say 127.0. 0.1 , you might find port 445 open on your machine. TCP port 445 is used for direct TCP/IP MS Networking access without the need for a NetBIOS layer.

According to my experience, some ports may not show up with that local host port (127....) and tha's why I would recommend using the IP address from ipconfig/all command.

🔹 Running The Script

So I ran my script like this: py port_scanner.py and this is the output so far: image.png

GitHub Repo

Note: Port-Scanning can take a while unless you specifically identify certain ports to scan.

🔸 Notes 📑

You can read further here about ports and Python network programming;

✔ Learn more about ports here and see why you should close or open some.
✔ Read about socket module here
✔ The dangers of open port 139 - TechTarget
✔ Common computer network ports - Open Source Article
✔ The Complete Python Network Programming Udemy Course for 2022
✔ Socket programming with Python Org tutorial

🔸 Conclusion ✌

This article is for educational purposes and I am not responsible for any intended personal use case.

That's it!

If you enjoyed this article, consider subscribing to my channel for related content especially about Tech, Python & Programming.

📢Follow me on Twitter:♥ ♥

Ronnie Atuhaire