From 105c7ffa86d857d9c8fcb4392f0e0db240ae0a51 Mon Sep 17 00:00:00 2001 From: PaganoBerserker <47154857+PaganoBerserker@users.noreply.github.com> Date: Wed, 11 Oct 2023 20:42:19 -0600 Subject: [PATCH 01/25] Update README.md --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 4d2a3da..ae392ff 100644 --- a/README.md +++ b/README.md @@ -1 +1,3 @@ -# Python_programs \ No newline at end of file +# Python_programs + +"I have uploaded a file with several Python codes that I believe will be of great help and contribution to the Python community. These codes address different topics and common problems in developing with Python, such as classification algorithms, data manipulation, visualization of graphics and much more. I hope this collection of code is useful to other Python developers and can foster knowledge sharing and community growth. I'm excited to share my work and contribute in this way!" From c543bfaafd4c5f36ef3b84a53d9302378144a690 Mon Sep 17 00:00:00 2001 From: PaganoBerserker <47154857+PaganoBerserker@users.noreply.github.com> Date: Wed, 11 Oct 2023 20:42:58 -0600 Subject: [PATCH 02/25] Create python-publish.yml --- .github/workflows/python-publish.yml | 39 ++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 .github/workflows/python-publish.yml diff --git a/.github/workflows/python-publish.yml b/.github/workflows/python-publish.yml new file mode 100644 index 0000000..bdaab28 --- /dev/null +++ b/.github/workflows/python-publish.yml @@ -0,0 +1,39 @@ +# This workflow will upload a Python Package using Twine when a release is created +# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries + +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. + +name: Upload Python Package + +on: + release: + types: [published] + +permissions: + contents: read + +jobs: + deploy: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Set up Python + uses: actions/setup-python@v3 + with: + python-version: '3.x' + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install build + - name: Build package + run: python -m build + - name: Publish package + uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29 + with: + user: __token__ + password: ${{ secrets.PYPI_API_TOKEN }} From 44c00042f74388dc0954ccae4b33623c988c8410 Mon Sep 17 00:00:00 2001 From: PaganoBerserker <47154857+PaganoBerserker@users.noreply.github.com> Date: Sat, 11 Nov 2023 20:08:47 -0600 Subject: [PATCH 03/25] 5 more programs done in 1 week. 5 more programs were created to practice python. --- PROGRAMAS DE PYTHON/Automata1.py | 40 +++++++++++++++++++++++ PROGRAMAS DE PYTHON/Automata2.py | 35 ++++++++++++++++++++ PROGRAMAS DE PYTHON/CalculadoraCientif.py | 39 ++++++++++++++++++++++ PROGRAMAS DE PYTHON/Funcion.py | 7 ++++ PROGRAMAS DE PYTHON/Lista.py | 24 ++++++++++++++ 5 files changed, 145 insertions(+) create mode 100644 PROGRAMAS DE PYTHON/Automata1.py create mode 100644 PROGRAMAS DE PYTHON/Automata2.py create mode 100644 PROGRAMAS DE PYTHON/CalculadoraCientif.py create mode 100644 PROGRAMAS DE PYTHON/Funcion.py create mode 100644 PROGRAMAS DE PYTHON/Lista.py diff --git a/PROGRAMAS DE PYTHON/Automata1.py b/PROGRAMAS DE PYTHON/Automata1.py new file mode 100644 index 0000000..179eb66 --- /dev/null +++ b/PROGRAMAS DE PYTHON/Automata1.py @@ -0,0 +1,40 @@ +automata = { + 'estados': {'q0', 'q1', 'q2', 'q3', 'q4'}, + 'alfabeto': {'0', '1'}, + 'estado_inicial': 'q0', + 'estados_aceptacion': {'q3', 'q4'}, + 'transiciones': { + ('q0', '0'): 'q1', + ('q0', '1'): 'q2', + ('q1', '0'): 'q3', + ('q1', '1'): 'q2', + ('q2', '0'): 'q2', + ('q2', '1'): 'q4', + ('q3', '0'): 'q3', + ('q3', '1'): 'q4', + ('q4', '0'): 'q4', + ('q4', '1'): 'q4' + } +} + +def simular_automata(automata, cadena): + estado_actual = automata['estado_inicial'] + for simbolo in cadena: + if (estado_actual, simbolo) in automata['transiciones']: + estado_actual = automata['transiciones'][(estado_actual, simbolo)] + else: + return False + return estado_actual in automata['estados_aceptacion'] + +cadena1 = '0011' +cadena2 = '0110' + +if simular_automata(automata, cadena1): + print(f'La cadena "{cadena1}" es aceptada por el autómata.') +else: + print(f'La cadena "{cadena1}" no es aceptada por el autómata.') + +if simular_automata(automata, cadena2): + print(f'La cadena "{cadena2}" es aceptada por el autómata.') +else: + print(f'La cadena "{cadena2}" no es aceptada por el autómata.') diff --git a/PROGRAMAS DE PYTHON/Automata2.py b/PROGRAMAS DE PYTHON/Automata2.py new file mode 100644 index 0000000..95e4656 --- /dev/null +++ b/PROGRAMAS DE PYTHON/Automata2.py @@ -0,0 +1,35 @@ +automata = { + 'estados': {'q0', 'q1', 'q2', 'q3', 'q4'}, + 'alfabeto': {'0', '1'}, + 'estado_inicial': 'q0', + 'estados_aceptacion': {'q3', 'q4'}, + 'transiciones': { + ('q0', '0'): 'q1', + ('q0', '1'): 'q2', + ('q1', '0'): 'q3', + ('q1', '1'): 'q2', + ('q2', '0'): 'q2', + ('q2', '1'): 'q4', + ('q3', '0'): 'q3', + ('q3', '1'): 'q4', + ('q4', '0'): 'q4', + ('q4', '1'): 'q4' + } +} + +def simular_automata(automata, cadena): + estado_actual = automata['estado_inicial'] + for simbolo in cadena: + if (estado_actual, simbolo) in automata['transiciones']: + estado_actual = automata['transiciones'][(estado_actual, simbolo)] + else: + return False + return estado_actual in automata['estados_aceptacion'] + +cadena = input("Ingrese una cadena: ") + +if simular_automata(automata, cadena): + print(f'La cadena "{cadena}" es aceptada por el autómata.') +else: + print(f'La cadena "{cadena}" no es aceptada por el autómata.') + diff --git a/PROGRAMAS DE PYTHON/CalculadoraCientif.py b/PROGRAMAS DE PYTHON/CalculadoraCientif.py new file mode 100644 index 0000000..fd8fbc5 --- /dev/null +++ b/PROGRAMAS DE PYTHON/CalculadoraCientif.py @@ -0,0 +1,39 @@ +import math + +def suma(a, b): + return a + b + +def resta(a, b): + return a - b + +def multiplicacion(a, b): + return a * b + +def division(a, b): + return a / b + +def potencia(a, b): + return a ** b + +def raiz_cuadrada(a): + return math.sqrt(a) + +def seno(a): + return math.sin(a) + +def coseno(a): + return math.cos(a) + +def tangente(a): + return math.tan(a) + +# Ejemplo de uso +print(suma(5, 3)) # Output: 8 +print(resta(10, 4)) # Output: 6 +print(multiplicacion(2, 6)) # Output: 12 +print(division(15, 3)) # Output: 5 +print(potencia(2, 3)) # Output: 8 +print(raiz_cuadrada(16)) # Output: 4 +print(seno(math.pi/2)) # Output: 1.0 +print(coseno(0)) # Output: 1.0 +print(tangente(math.pi/4)) # Output: 1.0 diff --git a/PROGRAMAS DE PYTHON/Funcion.py b/PROGRAMAS DE PYTHON/Funcion.py new file mode 100644 index 0000000..a2e693a --- /dev/null +++ b/PROGRAMAS DE PYTHON/Funcion.py @@ -0,0 +1,7 @@ +def saludar_persona(): + nombre = input("Por favor, ingresa tu nombre: ") + mensaje = f"Hola, {nombre}! ¡Bienvenido!" + return mensaje + +saludo = saludar_persona() +print(saludo) diff --git a/PROGRAMAS DE PYTHON/Lista.py b/PROGRAMAS DE PYTHON/Lista.py new file mode 100644 index 0000000..9b58cfa --- /dev/null +++ b/PROGRAMAS DE PYTHON/Lista.py @@ -0,0 +1,24 @@ +# Crear una lista vacía para almacenar la asistencia +asistencia = [] + +while True: + # Solicitar al usuario que ingrese el nombre del estudiante o 'q' para salir + nombre = input("Ingresa el nombre del estudiante (o 'q' para salir): ") + + if nombre.lower() == 'q': + break # Salir del bucle si se ingresa 'q' + + # Agregar el nombre del estudiante a la lista de asistencia + asistencia.append(nombre) + +# Mostrar la lista de asistencia +print("Lista de Asistencia:") +for estudiante in asistencia: + print(estudiante) + +# Guardar la lista de asistencia en un archivo de texto +with open("asistencia.txt", "w") as archivo: + for estudiante in asistencia: + archivo.write(estudiante + "\n") + +print("La lista de asistencia se ha guardado en 'asistencia.txt'.") From 125b734b52c61496f9c321bae11aa1189901be91 Mon Sep 17 00:00:00 2001 From: PaganoBerserker <47154857+PaganoBerserker@users.noreply.github.com> Date: Tue, 9 Apr 2024 20:48:54 -0600 Subject: [PATCH 04/25] Updating my Python programs. Programs to make functions and Maching Learning in python. --- PROGRAMAS DE PYTHON/Hash.py | 98 +++++++++++++++++++++ PROGRAMAS DE PYTHON/ML1.py | 31 +++++++ PROGRAMAS DE PYTHON/Pandas1.py | 13 +++ PROGRAMAS DE PYTHON/arbol.py | 33 +++++++ PROGRAMAS DE PYTHON/asistencia.txt | 21 +++++ PROGRAMAS DE PYTHON/audios.py | 22 +++++ PROGRAMAS DE PYTHON/datos_transacciones.csv | 4 + PROGRAMAS DE PYTHON/seguridad.py | 45 ++++++++++ 8 files changed, 267 insertions(+) create mode 100644 PROGRAMAS DE PYTHON/Hash.py create mode 100644 PROGRAMAS DE PYTHON/ML1.py create mode 100644 PROGRAMAS DE PYTHON/Pandas1.py create mode 100644 PROGRAMAS DE PYTHON/arbol.py create mode 100644 PROGRAMAS DE PYTHON/asistencia.txt create mode 100644 PROGRAMAS DE PYTHON/audios.py create mode 100644 PROGRAMAS DE PYTHON/datos_transacciones.csv create mode 100644 PROGRAMAS DE PYTHON/seguridad.py diff --git a/PROGRAMAS DE PYTHON/Hash.py b/PROGRAMAS DE PYTHON/Hash.py new file mode 100644 index 0000000..1c48b46 --- /dev/null +++ b/PROGRAMAS DE PYTHON/Hash.py @@ -0,0 +1,98 @@ +class HashNode: + def __init__(self, key, value): + self.key = key + self.value = value + self.deleted = False + +class HashTable: + def __init__(self, initial_size=16): + self.size = initial_size + self.table = [None] * self.size + self.used_slots = 0 + self.deleted_slots = 0 + self.load_factor = 0.5 + self._resize_threshold = int(self.size * self.load_factor) + + def _hash_function(self, key): + return hash(key) % self.size + + def _double_hash(self, key, attempt): + return (self._hash_function(key) + attempt * (1 + hash(key) % (self.size - 1))) % self.size + + def _resize_table(self): + self.size *= 2 + new_table = [None] * self.size + + for node in filter(None, self.table): + index = self._find_empty_slot(new_table, node.key) + new_table[index] = node + + self.table = new_table + self._resize_threshold = int(self.size * self.load_factor) + + def _find_empty_slot(self, table, key): + attempt = 0 + index = self._double_hash(key, attempt) + while table[index] is not None and not table[index].deleted: + print(f"Collision at index {index} for key {key}. Trying next index.") + attempt += 1 + index = self._double_hash(key, attempt) + return index + + def insert(self, key, value): + if self.used_slots + self.deleted_slots >= self._resize_threshold: + print(f"Resizing table (current size: {self.size}).") + self._resize_table() + + attempt = 0 + index = self._find_empty_slot(self.table, key) + + if self.table[index] is None or self.table[index].deleted: + print(f"Inserting key {key} at index {index}.") + self.table[index] = HashNode(key, value) + self.used_slots += 1 + else: + print(f"Updating value for key {key} at index {index}.") + self.table[index].value = value + + def search(self, key): + attempt = 0 + index = self._double_hash(key, attempt) + + while self.table[index] is not None: + if not self.table[index].deleted and self.table[index].key == key: + print(f"Key {key} found at index {index}.") + return self.table[index].value + attempt += 1 + index = self._double_hash(key, attempt) + + raise KeyError(f"Key not found: {key}") + + def delete(self, key): + attempt = 0 + index = self._double_hash(key, attempt) + + while self.table[index] is not None: + if not self.table[index].deleted and self.table[index].key == key: + print(f"Deleting key {key} at index {index}.") + self.table[index].deleted = True + self.deleted_slots += 1 + self.used_slots -= 1 + return + attempt += 1 + index = self._double_hash(key, attempt) + + raise KeyError(f"Key not found: {key}") + +# Ejemplo de uso +hash_table = HashTable() +for i in range(1000): + hash_table.insert(f"key_{i}", f"value_{i}") + +print(hash_table.search("key_42")) + +hash_table.delete("key_42") +try: + print(hash_table.search("key_42")) +except KeyError as e: + print(e) diff --git a/PROGRAMAS DE PYTHON/ML1.py b/PROGRAMAS DE PYTHON/ML1.py new file mode 100644 index 0000000..fdf6b7b --- /dev/null +++ b/PROGRAMAS DE PYTHON/ML1.py @@ -0,0 +1,31 @@ +# Paso 1: Preparación de los Datos +import pandas as pd +from sklearn.model_selection import train_test_split + +# Cargar datos +data = pd.read_csv("datos_transacciones.csv") + +# Dividir datos en entrenamiento y prueba +X = data.drop("fraude", axis=1) # Características +y = data["fraude"] # Etiquetas +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) + +# Paso 2: Entrenamiento del Modelo +from sklearn.ensemble import RandomForestClassifier + +# Crear y entrenar el modelo +model = RandomForestClassifier() +model.fit(X_train, y_train) + +# Paso 3: Evaluación del Modelo +from sklearn.metrics import classification_report, confusion_matrix + +# Evaluar el modelo +y_pred = model.predict(X_test) +print("Matriz de Confusión:") +print(confusion_matrix(y_test, y_pred)) +print("Reporte de Clasificación:") +print(classification_report(y_test, y_pred)) + +# Paso 4: Implementación del Modelo +# Ahora puedes usar "model" para predecir fraudes en nuevas transacciones diff --git a/PROGRAMAS DE PYTHON/Pandas1.py b/PROGRAMAS DE PYTHON/Pandas1.py new file mode 100644 index 0000000..027ab5c --- /dev/null +++ b/PROGRAMAS DE PYTHON/Pandas1.py @@ -0,0 +1,13 @@ +import pandas as pd + +# Cargar datos desde un archivo CSV +data = pd.read_csv("datos.csv") + +# Mostrar las primeras filas del DataFrame +print(data.head()) + +# Resumen estadístico del DataFrame +print(data.describe()) + +# Información sobre el DataFrame +print(data.info()) diff --git a/PROGRAMAS DE PYTHON/arbol.py b/PROGRAMAS DE PYTHON/arbol.py new file mode 100644 index 0000000..24bdedc --- /dev/null +++ b/PROGRAMAS DE PYTHON/arbol.py @@ -0,0 +1,33 @@ +from sklearn.tree import DecisionTreeClassifier +from sklearn.model_selection import train_test_split +from sklearn import metrics + +# Datos de ejemplo +# X representará las características (condiciones climáticas) y y será la etiqueta (deberías llevar un paraguas o no) +X = [[0, 1], [1, 0], [1, 1], [0, 0], [2, 2], [2, 0], [2, 1]] +y = [1, 1, 1, 0, 1, 0, 1] # 1: llevar paraguas, 0: no llevar paraguas + +# Dividir los datos en conjunto de entrenamiento y conjunto de prueba +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) + +# Crear el clasificador de árbol de decisión +clf = DecisionTreeClassifier() + +# Entrenar el modelo +clf.fit(X_train, y_train) + +# Hacer predicciones en el conjunto de prueba +y_pred = clf.predict(X_test) + +# Evaluar la precisión del modelo +accuracy = metrics.accuracy_score(y_test, y_pred) +print(f"Precisión del modelo: {accuracy * 100:.2f}%") + +# Ahora puedes utilizar el modelo para predecir si debes llevar un paraguas para nuevas condiciones climáticas +new_conditions = [[0, 1]] # Ejemplo: no está lloviendo, pero hay viento +prediction = clf.predict(new_conditions) + +if prediction[0] == 1: + print("Deberías llevar un paraguas.") +else: + print("No necesitas llevar un paraguas.") diff --git a/PROGRAMAS DE PYTHON/asistencia.txt b/PROGRAMAS DE PYTHON/asistencia.txt new file mode 100644 index 0000000..320a18e --- /dev/null +++ b/PROGRAMAS DE PYTHON/asistencia.txt @@ -0,0 +1,21 @@ +Gustavo +Paco +Clodomiro +x +x +x +x +xa +a +aq +w +s +ss +s +w +w + + +ss +s +sq diff --git a/PROGRAMAS DE PYTHON/audios.py b/PROGRAMAS DE PYTHON/audios.py new file mode 100644 index 0000000..ce6e1ae --- /dev/null +++ b/PROGRAMAS DE PYTHON/audios.py @@ -0,0 +1,22 @@ +import speech_recognition as sr + +def reconocer_voz(): + # Crear un objeto de reconocimiento de voz + r = sr.Recognizer() + + # Escuchar el audio del micrófono + with sr.Microphone() as source: + print("Di algo...") + audio = r.listen(source) + + # Intentar reconocer el texto + try: + texto = r.recognize_google(audio, language="es") + print("Has dicho: " + texto) + except sr.UnknownValueError: + print("No se pudo reconocer el audio") + except sr.RequestError as e: + print("Error al realizar la solicitud: {0}".format(e)) + +# Llamar a la función para iniciar el reconocimiento de voz +reconocer_voz() diff --git a/PROGRAMAS DE PYTHON/datos_transacciones.csv b/PROGRAMAS DE PYTHON/datos_transacciones.csv new file mode 100644 index 0000000..9ab6000 --- /dev/null +++ b/PROGRAMAS DE PYTHON/datos_transacciones.csv @@ -0,0 +1,4 @@ +monto,hora,ubicacion,tipo_tarjeta,fraude +100,13,EEUU,debito,0 +200,15,Canadá,credito,0 +500,10,México,debito,1 \ No newline at end of file diff --git a/PROGRAMAS DE PYTHON/seguridad.py b/PROGRAMAS DE PYTHON/seguridad.py new file mode 100644 index 0000000..72a30a7 --- /dev/null +++ b/PROGRAMAS DE PYTHON/seguridad.py @@ -0,0 +1,45 @@ +import hashlib +import datetime + +class Block: + def __init__(self, index, previous_hash, timestamp, data, hash): + self.index = index + self.previous_hash = previous_hash + self.timestamp = timestamp + self.data = data + self.hash = hash + +def calculate_hash(index, previous_hash, timestamp, data): + value = str(index) + str(previous_hash) + str(timestamp) + str(data) + return hashlib.sha256(value.encode('utf-8')).hexdigest() + +def create_genesis_block(): + # Datos iniciales del bloque génesis + return Block(0, "0", datetime.datetime.now(), "Datos iniciales", calculate_hash(0, "0", datetime.datetime.now(), "Datos iniciales")) + +def create_new_block(previous_block, data): + index = previous_block.index + 1 + timestamp = datetime.datetime.now() + hash = calculate_hash(index, previous_block.hash, timestamp, data) + return Block(index, previous_block.hash, timestamp, data, hash) + +# Crear la cadena de bloques +blockchain = [create_genesis_block()] +previous_block = blockchain[0] + +# Añadir bloques a la cadena de bloques +blocks_to_add = 5 +for i in range(1, blocks_to_add + 1): + new_data = f'Datos del bloque {i}' + new_block = create_new_block(previous_block, new_data) + blockchain.append(new_block) + previous_block = new_block + +# Imprimir la cadena de bloques +for block in blockchain: + print(f"Index: {block.index}") + print(f"Previous Hash: {block.previous_hash}") + print(f"Timestamp: {block.timestamp}") + print(f"Data: {block.data}") + print(f"Hash: {block.hash}") + print("\n") From b3e8e292f5fea15d3d0e679f3dc955f7a08bce20 Mon Sep 17 00:00:00 2001 From: PaganoBerserker <47154857+PaganoBerserker@users.noreply.github.com> Date: Tue, 9 Apr 2024 21:01:26 -0600 Subject: [PATCH 05/25] IPTables 1 This is a basic example of how you can add and delete rules in IPTables using Python. Note that these commands will need superuser permissions to run, so you may need to run your Python script with administrator privileges. This is a basic example of how you can add and delete rules in IPTables using Python. Note that these commands will need superuser permissions to run, so you may need to run your Python script with administrator privileges. --- PROGRAMAS DE PYTHON/IPTables1.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 PROGRAMAS DE PYTHON/IPTables1.py diff --git a/PROGRAMAS DE PYTHON/IPTables1.py b/PROGRAMAS DE PYTHON/IPTables1.py new file mode 100644 index 0000000..741fd67 --- /dev/null +++ b/PROGRAMAS DE PYTHON/IPTables1.py @@ -0,0 +1,17 @@ +import subprocess + +# Función para agregar una regla al firewall IPTables +def agregar_regla(accion, protocolo, puerto): + comando = f"iptables -A INPUT -p {protocolo} --dport {puerto} -j {accion}" + subprocess.run(comando, shell=True) + +# Función para eliminar una regla del firewall IPTables +def eliminar_regla(accion, protocolo, puerto): + comando = f"iptables -D INPUT -p {protocolo} --dport {puerto} -j {accion}" + subprocess.run(comando, shell=True) + +# Agregar una regla para permitir conexiones TCP en el puerto 80 (HTTP) +agregar_regla("ACCEPT", "tcp", 80) + +# Eliminar la regla anterior +eliminar_regla("ACCEPT", "tcp", 80) From b4ce6cf403e34d93812a769685b0ea1f0f1f9ac7 Mon Sep 17 00:00:00 2001 From: PaganoBerserker <47154857+PaganoBerserker@users.noreply.github.com> Date: Tue, 9 Apr 2024 21:04:52 -0600 Subject: [PATCH 06/25] Allow SSH Traffic (Port 22) This script will add a rule to the IPTables firewall to allow SSH (Secure Shell) traffic on port 22. --- PROGRAMAS DE PYTHON/IPTables2.py | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 PROGRAMAS DE PYTHON/IPTables2.py diff --git a/PROGRAMAS DE PYTHON/IPTables2.py b/PROGRAMAS DE PYTHON/IPTables2.py new file mode 100644 index 0000000..6781791 --- /dev/null +++ b/PROGRAMAS DE PYTHON/IPTables2.py @@ -0,0 +1,7 @@ +import subprocess + +def permitir_ssh(): + comando = "iptables -A INPUT -p tcp --dport 22 -j ACCEPT" + subprocess.run(comando, shell=True) + +permitir_ssh() From 92c6a9a482346e71bdbd55792d74fc69cd8cd981 Mon Sep 17 00:00:00 2001 From: PaganoBerserker <47154857+PaganoBerserker@users.noreply.github.com> Date: Tue, 9 Apr 2024 21:06:57 -0600 Subject: [PATCH 07/25] Configure Rules Based on Specific Packages This script will set a custom rule on the IPTables firewall that allows or blocks traffic from a specific source IP address to a specific destination IP address and port. --- PROGRAMAS DE PYTHON/IPTables3.py | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 PROGRAMAS DE PYTHON/IPTables3.py diff --git a/PROGRAMAS DE PYTHON/IPTables3.py b/PROGRAMAS DE PYTHON/IPTables3.py new file mode 100644 index 0000000..cd11313 --- /dev/null +++ b/PROGRAMAS DE PYTHON/IPTables3.py @@ -0,0 +1,8 @@ +import subprocess + +def establecer_regla_personalizada(ip_origen, ip_destino, puerto, accion): + comando = f"iptables -A INPUT -s {ip_origen} -d {ip_destino} -p tcp --dport {puerto} -j {accion}" + subprocess.run(comando, shell=True) + +establecer_regla_personalizada("192.168.1.100", "192.168.1.200", 22, "ACCEPT") + From dcf25bc2df36e8059a69bef72bb03b87d9604302 Mon Sep 17 00:00:00 2001 From: PaganoBerserker <47154857+PaganoBerserker@users.noreply.github.com> Date: Thu, 11 Apr 2024 04:38:31 -0600 Subject: [PATCH 08/25] Species Classifier In this example, we will use a data set of Iris flowers to create a flower species classifier based on their characteristics. --- PROGRAMAS DE PYTHON/prediccion.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 PROGRAMAS DE PYTHON/prediccion.py diff --git a/PROGRAMAS DE PYTHON/prediccion.py b/PROGRAMAS DE PYTHON/prediccion.py new file mode 100644 index 0000000..1e29566 --- /dev/null +++ b/PROGRAMAS DE PYTHON/prediccion.py @@ -0,0 +1,28 @@ +from sklearn.datasets import load_iris +from sklearn.model_selection import train_test_split +from sklearn.neighbors import KNeighborsClassifier +from sklearn.metrics import accuracy_score + +# Paso 1: Cargar el conjunto de datos +iris = load_iris() +X = iris.data +y = iris.target + +# Paso 2: Dividir el conjunto de datos en conjuntos de entrenamiento y prueba +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) + +# Paso 3: Crear y entrenar el modelo +clf = KNeighborsClassifier(n_neighbors=3) +clf.fit(X_train, y_train) + +# Paso 4: Realizar predicciones +y_pred = clf.predict(X_test) + +# Paso 5: Evaluar el rendimiento del modelo +precision = accuracy_score(y_test, y_pred) +print("Precisión del modelo:", precision) + +# Paso 6: Utilizar el modelo para hacer predicciones nuevas +nuevas_caracteristicas = [[5.1, 3.5, 1.4, 0.2]] # Nuevas características de una flor +prediccion = clf.predict(nuevas_caracteristicas) +print("Predicción:", iris.target_names[prediccion]) From 0424b5eb298907e44a0305f0e670d1ca2989aaeb Mon Sep 17 00:00:00 2001 From: PaganoBerserker <47154857+PaganoBerserker@users.noreply.github.com> Date: Thu, 11 Apr 2024 20:30:44 -0600 Subject: [PATCH 09/25] Generate a new 2048-bit RSA key RSA key securely and then serialize it into PEM format before loading it. --- PROGRAMAS DE PYTHON/bosquealeatorio.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 PROGRAMAS DE PYTHON/bosquealeatorio.py diff --git a/PROGRAMAS DE PYTHON/bosquealeatorio.py b/PROGRAMAS DE PYTHON/bosquealeatorio.py new file mode 100644 index 0000000..391b2b3 --- /dev/null +++ b/PROGRAMAS DE PYTHON/bosquealeatorio.py @@ -0,0 +1,22 @@ +from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.hazmat.primitives import serialization + +# Generar una nueva clave RSA de 2048 bits +private_key = rsa.generate_private_key( + public_exponent=65537, + key_size=2048, +) + +# Serializar la clave en formato PEM +pem = private_key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.NoEncryption(), +) + +# Cargar la clave serializada +loaded_private_key = serialization.load_pem_private_key(pem, password=None) + +# Imprimir la clave cargada +print(loaded_private_key) + From e0428b050910bc06120cdecdd192b1c62fe5646d Mon Sep 17 00:00:00 2001 From: PaganoBerserker <47154857+PaganoBerserker@users.noreply.github.com> Date: Sat, 13 Apr 2024 03:59:53 -0600 Subject: [PATCH 10/25] Random Forest Random forest for encryption From bc9d937f23d4075329343f973f571c230a7a1f06 Mon Sep 17 00:00:00 2001 From: PaganoBerserker <47154857+PaganoBerserker@users.noreply.github.com> Date: Mon, 15 Apr 2024 04:25:50 -0600 Subject: [PATCH 11/25] vulnerability analyst This code assumes that you have a CSV file called "vulnerabilities_data.csv" that contains the data for vulnerabilities in the security system, where each row represents an instance of data and the "vulnerable" column indicates whether the system is vulnerable or not. --- PROGRAMAS DE PYTHON/vulnerabilidad.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 PROGRAMAS DE PYTHON/vulnerabilidad.py diff --git a/PROGRAMAS DE PYTHON/vulnerabilidad.py b/PROGRAMAS DE PYTHON/vulnerabilidad.py new file mode 100644 index 0000000..37519ad --- /dev/null +++ b/PROGRAMAS DE PYTHON/vulnerabilidad.py @@ -0,0 +1,22 @@ +import pandas as pd +from sklearn.model_selection import train_test_split +from sklearn.ensemble import RandomForestClassifier +from sklearn.metrics import classification_report + +# Cargar los datos de vulnerabilidades en el sistema de seguridad +data = pd.read_csv("datos_vulnerabilidades.csv") + +# Preprocesamiento de datos (eliminación de valores nulos, codificación de variables categóricas, etc.) + +# Dividir los datos en conjuntos de entrenamiento y prueba +X = data.drop("vulnerable", axis=1) +y = data["vulnerable"] +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) + +# Entrenar un clasificador de bosque aleatorio +clf = RandomForestClassifier() +clf.fit(X_train, y_train) + +# Evaluar el modelo +y_pred = clf.predict(X_test) +print(classification_report(y_test, y_pred)) From fd227267c494124b433a9d13304931b44ce0bf8b Mon Sep 17 00:00:00 2001 From: PaganoBerserker <47154857+PaganoBerserker@users.noreply.github.com> Date: Mon, 15 Apr 2024 04:28:23 -0600 Subject: [PATCH 12/25] vulnerability analyst In this example, security event logs are used to detect system anomalies. Relevant features are selected from the data and normalized before training the model. The Isolation Forest algorithm is used, which is effective in detecting anomalies in large and multidimensional data sets. The model predictions are evaluated using classification metrics, such as precision, recall, and F1-score. --- PROGRAMAS DE PYTHON/vulnerabilidad2.py | 31 ++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 PROGRAMAS DE PYTHON/vulnerabilidad2.py diff --git a/PROGRAMAS DE PYTHON/vulnerabilidad2.py b/PROGRAMAS DE PYTHON/vulnerabilidad2.py new file mode 100644 index 0000000..f9883aa --- /dev/null +++ b/PROGRAMAS DE PYTHON/vulnerabilidad2.py @@ -0,0 +1,31 @@ +import pandas as pd +import numpy as np +from sklearn.ensemble import IsolationForest +from sklearn.preprocessing import StandardScaler +from sklearn.model_selection import train_test_split +from sklearn.metrics import classification_report + +# Cargar los datos de los registros de eventos de seguridad +data = pd.read_csv("datos_registros_eventos.csv") + +# Seleccionar las características relevantes y normalizar los datos +X = data[['feature1', 'feature2', 'feature3']] +scaler = StandardScaler() +X_scaled = scaler.fit_transform(X) + +# Dividir los datos en conjuntos de entrenamiento y prueba +X_train, X_test = train_test_split(X_scaled, test_size=0.2, random_state=42) + +# Entrenar un modelo de detección de anomalías con Isolation Forest +clf = IsolationForest(contamination=0.05) +clf.fit(X_train) + +# Predecir las anomalías en los datos de prueba +y_pred = clf.predict(X_test) + +# Evaluar las predicciones +y_pred[y_pred == 1] = 0 # Anomalía si el valor es 1 +y_pred[y_pred == -1] = 1 # No anomalía si el valor es -1 + +# Imprimir métricas de evaluación del modelo +print(classification_report(y_test, y_pred)) From d06dc769e95a47f7315eee390cc92519c7485e02 Mon Sep 17 00:00:00 2001 From: PaganoBerserker <47154857+PaganoBerserker@users.noreply.github.com> Date: Mon, 15 Apr 2024 04:30:35 -0600 Subject: [PATCH 13/25] vulnerability analyst MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In this example, we first load data from the NSL-KDD dataset, which contains network activity logs labeled as benign or malicious. Then, we perform the necessary data preprocessing, such as removing non-relevant columns and encoding categorical variables. After splitting the data into training and test sets, we normalize the features so that they have a mean of zero and a standard deviation of one. Then, we use a neural network classifier (MLPClassifier) ​​to train the model on the training set. Finally, we make predictions on the test set and evaluate the performance of the model using classification metrics, such as precision, recall, and F1-score. --- PROGRAMAS DE PYTHON/vulnerabilidad3.py | 33 ++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 PROGRAMAS DE PYTHON/vulnerabilidad3.py diff --git a/PROGRAMAS DE PYTHON/vulnerabilidad3.py b/PROGRAMAS DE PYTHON/vulnerabilidad3.py new file mode 100644 index 0000000..9f4c6d5 --- /dev/null +++ b/PROGRAMAS DE PYTHON/vulnerabilidad3.py @@ -0,0 +1,33 @@ +import pandas as pd +from sklearn.preprocessing import StandardScaler +from sklearn.model_selection import train_test_split +from sklearn.neural_network import MLPClassifier +from sklearn.metrics import classification_report + +# Cargar los datos del conjunto de datos NSL-KDD +data = pd.read_csv("nsl-kdd.csv") + +# Preprocesamiento de datos +# Eliminar columnas no relevantes y codificar variables categóricas + +# Separar características y etiquetas +X = data.drop("label", axis=1) +y = data["label"] + +# Dividir los datos en conjuntos de entrenamiento y prueba +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) + +# Normalizar los datos +scaler = StandardScaler() +X_train = scaler.fit_transform(X_train) +X_test = scaler.transform(X_test) + +# Entrenar un clasificador de redes neuronales +clf = MLPClassifier(hidden_layer_sizes=(100, 50), max_iter=1000, random_state=42) +clf.fit(X_train, y_train) + +# Realizar predicciones en el conjunto de prueba +y_pred = clf.predict(X_test) + +# Imprimir métricas de evaluación del modelo +print(classification_report(y_test, y_pred)) From 655e103f8e981915198933c82338a0a93bbdcf08 Mon Sep 17 00:00:00 2001 From: PaganoBerserker <47154857+PaganoBerserker@users.noreply.github.com> Date: Mon, 15 Apr 2024 04:32:53 -0600 Subject: [PATCH 14/25] vulneravility analyst In this example, we first load data from the CICIDS 2017 dataset, which contains labeled network traffic logs. Then, we perform the necessary data preprocessing, such as removing non-relevant columns and encoding categorical variables. After normalizing the data, we use the DBSCAN (Density-Based Spatial Clustering of Applications with Noise) algorithm to detect anomalies in the data set. DBSCAN is an unsupervised clustering algorithm that can identify high-density regions in the feature space, making it suitable for anomaly detection in network traffic data sets. Finally, we assign anomaly (-1) and non-anomaly (1) labels to the data and evaluate the model performance using classification metrics. This advanced approach allows us to detect denial of service attacks in a network environment using unsupervised learning techniques. --- PROGRAMAS DE PYTHON/vulnerabilidad4.py | 30 ++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 PROGRAMAS DE PYTHON/vulnerabilidad4.py diff --git a/PROGRAMAS DE PYTHON/vulnerabilidad4.py b/PROGRAMAS DE PYTHON/vulnerabilidad4.py new file mode 100644 index 0000000..487fcba --- /dev/null +++ b/PROGRAMAS DE PYTHON/vulnerabilidad4.py @@ -0,0 +1,30 @@ +import pandas as pd +from sklearn.preprocessing import StandardScaler +from sklearn.cluster import DBSCAN +from sklearn.metrics import classification_report + +# Cargar los datos del conjunto de datos CICIDS 2017 +data = pd.read_csv("cicids_2017.csv") + +# Preprocesamiento de datos +# Eliminar columnas no relevantes y codificar variables categóricas + +# Separar características y etiquetas +X = data.drop("label", axis=1) +y = data["label"] + +# Normalizar los datos +scaler = StandardScaler() +X_scaled = scaler.fit_transform(X) + +# Entrenar un modelo de detección de anomalías con DBSCAN +clf = DBSCAN(eps=0.5, min_samples=10) +clf.fit(X_scaled) + +# Asignar etiquetas de anomalía (-1) y no anomalía (1) a los datos +y_pred = clf.labels_ +y_pred[y_pred == 0] = 1 # Clases identificadas como normales +y_pred[y_pred == -1] = 0 # Clases identificadas como anormales + +# Imprimir métricas de evaluación del modelo +print(classification_report(y, y_pred)) From b21cef919e27e7c2707ee1bda67ad6ed6c3c22f2 Mon Sep 17 00:00:00 2001 From: PaganoBerserker <47154857+PaganoBerserker@users.noreply.github.com> Date: Mon, 15 Apr 2024 04:37:44 -0600 Subject: [PATCH 15/25] Vulnerality Analyst 6 In this example, we first load the data from the email dataset, where each email is labeled as phishing or legitimate. We then preprocess the data by tokenizing the text in the emails and converting them into numerical sequences. We build a CNN model using embedding layers to convert words into dense vectors, convolutional layers to extract important features from the text, and dense layers for final classification. We train the model on the training data and evaluate it on the test set. This advanced approach uses deep learning and natural language processing to detect phishing attacks in emails, leveraging the capabilities of convolutional neural networks to learn complex patterns in text data. --- PROGRAMAS DE PYTHON/vulnerabilidad6.py | 55 ++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 PROGRAMAS DE PYTHON/vulnerabilidad6.py diff --git a/PROGRAMAS DE PYTHON/vulnerabilidad6.py b/PROGRAMAS DE PYTHON/vulnerabilidad6.py new file mode 100644 index 0000000..780b29d --- /dev/null +++ b/PROGRAMAS DE PYTHON/vulnerabilidad6.py @@ -0,0 +1,55 @@ +import pandas as pd +from sklearn.model_selection import train_test_split +from sklearn.preprocessing import LabelEncoder +from tensorflow.keras.preprocessing.text import Tokenizer +from tensorflow.keras.preprocessing.sequence import pad_sequences +from tensorflow.keras.models import Sequential +from tensorflow.keras.layers import Embedding, Conv1D, MaxPooling1D, Flatten, Dense + +# Cargar los datos del conjunto de datos de correos electrónicos +data = pd.read_csv("phishing_emails.csv") + +# Preprocesamiento de datos +X = data['email_text'] +y = data['label'] + +# Codificar las etiquetas de clase +label_encoder = LabelEncoder() +y = label_encoder.fit_transform(y) + +# Tokenizar el texto de los correos electrónicos y convertirlos en secuencias numéricas +tokenizer = Tokenizer() +tokenizer.fit_on_texts(X) +X_sequences = tokenizer.texts_to_sequences(X) + +# Ajustar las secuencias a una longitud fija y crear un arreglo numpy +max_sequence_length = 1000 # longitud máxima de la secuencia +X_pad = pad_sequences(X_sequences, maxlen=max_sequence_length) + +# Dividir los datos en conjuntos de entrenamiento y prueba +X_train, X_test, y_train, y_test = train_test_split(X_pad, y, test_size=0.2, random_state=42) + +# Construir el modelo de CNN +embedding_dim = 50 # dimensión del embedding +vocab_size = len(tokenizer.word_index) + 1 # tamaño del vocabulario + +model = Sequential([ + Embedding(vocab_size, embedding_dim, input_length=max_sequence_length), + Conv1D(128, 5, activation='relu'), + MaxPooling1D(5), + Conv1D(128, 5, activation='relu'), + MaxPooling1D(5), + Flatten(), + Dense(128, activation='relu'), + Dense(1, activation='sigmoid') +]) + +model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) + +# Entrenar el modelo +model.fit(X_train, y_train, epochs=5, batch_size=32, validation_data=(X_test, y_test)) + +# Evaluar el modelo en el conjunto de prueba +loss, accuracy = model.evaluate(X_test, y_test) +print(f"Pérdida en el conjunto de prueba: {loss}") +print(f"Precisión en el conjunto de prueba: {accuracy}") From 1a97a0c229356f0036b2a3e81396c86903f908a3 Mon Sep 17 00:00:00 2001 From: Berserker <47154857+TrinityBerserker@users.noreply.github.com> Date: Wed, 3 Jul 2024 01:53:37 -0600 Subject: [PATCH 16/25] A file computer A file computer (Tells you what order your files should be in). --- PROGRAMAS DE PYTHON/ordenadordearchivos.py | 24 ++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 PROGRAMAS DE PYTHON/ordenadordearchivos.py diff --git a/PROGRAMAS DE PYTHON/ordenadordearchivos.py b/PROGRAMAS DE PYTHON/ordenadordearchivos.py new file mode 100644 index 0000000..93f41aa --- /dev/null +++ b/PROGRAMAS DE PYTHON/ordenadordearchivos.py @@ -0,0 +1,24 @@ +import os + +def ordenar_archivos_por_nombre(ruta_carpeta): + # Verificar si la ruta es válida y es un directorio + if not os.path.isdir(ruta_carpeta): + print(f"La ruta especificada '{ruta_carpeta}' no es un directorio válido.") + return + + # Obtener la lista de archivos en la carpeta + archivos = os.listdir(ruta_carpeta) + + # Ordenar los archivos por nombre (orden alfabético) + archivos.sort() + + # Mostrar los archivos ordenados + print(f"Archivos en '{ruta_carpeta}', ordenados alfabéticamente:") + for archivo in archivos: + print(archivo) + +# Solicitar la ruta de la carpeta al usuario +ruta = input("Ingrese la ruta de la carpeta que desea ordenar: ") + +# Llamar a la función para ordenar y mostrar los archivos +ordenar_archivos_por_nombre(ruta) From 0cdb735a7b94e1c1f03d3b2357d47eadadf86a0f Mon Sep 17 00:00:00 2001 From: Berserker <47154857+TrinityBerserker@users.noreply.github.com> Date: Wed, 3 Jul 2024 02:08:02 -0600 Subject: [PATCH 17/25] Automatic word corrector. Automatic word corrector. You can fix a file by entering the specific file path (including the file obviously). --- PROGRAMAS DE PYTHON/correctordepalabras.py | 39 ++++++++++++++++++++++ PROGRAMAS DE PYTHON/faltasdeorografia.txt | 1 + 2 files changed, 40 insertions(+) create mode 100644 PROGRAMAS DE PYTHON/correctordepalabras.py create mode 100644 PROGRAMAS DE PYTHON/faltasdeorografia.txt diff --git a/PROGRAMAS DE PYTHON/correctordepalabras.py b/PROGRAMAS DE PYTHON/correctordepalabras.py new file mode 100644 index 0000000..08595b1 --- /dev/null +++ b/PROGRAMAS DE PYTHON/correctordepalabras.py @@ -0,0 +1,39 @@ +import enchant + +def corregir_ortografia(archivo): + # Crear un diccionario de verificación ortográfica en inglés + d = enchant.Dict("en_US") + + # Leer el contenido del archivo + with open(archivo, 'r', encoding='utf-8') as f: + contenido = f.read() + + # Dividir el contenido en palabras + palabras = contenido.split() + + # Lista para almacenar las correcciones realizadas + correcciones = [] + + # Verificar ortografía y corregir palabras incorrectas + for palabra in palabras: + if not d.check(palabra): # Si la palabra no está en el diccionario + sugerencias = d.suggest(palabra) # Obtener sugerencias de corrección + if sugerencias: + correccion = sugerencias[0] # Tomar la primera sugerencia como corrección + correcciones.append((palabra, correccion)) # Guardar la palabra original y la corrección + contenido = contenido.replace(palabra, correccion) # Reemplazar en el contenido + + # Mostrar el contenido corregido por consola + print("Texto corregido:") + print(contenido) + + # Mostrar las correcciones realizadas + print("\nCorrecciones realizadas:") + for original, corregida in correcciones: + print(f"{original} -> {corregida}") + +# Solicitar al usuario el archivo que desea revisar +archivo = input("Ingrese el nombre del archivo que desea revisar (incluyendo la ruta si no está en el mismo directorio): ") + +# Llamar a la función para corregir ortografía y mostrar correcciones +corregir_ortografia(archivo) diff --git a/PROGRAMAS DE PYTHON/faltasdeorografia.txt b/PROGRAMAS DE PYTHON/faltasdeorografia.txt new file mode 100644 index 0000000..c2a6fd0 --- /dev/null +++ b/PROGRAMAS DE PYTHON/faltasdeorografia.txt @@ -0,0 +1 @@ +This text contains some spelling mistakes. For example, "teh", "problam", "occured", "writting", "abowt", "defenetly", "apologise", "seperate", "dissapointed", "begining", "beleive", "neccesary", "expeirence", "succesful", "sugestion", "ocassionally", "happened", "occured", "wether", "truely", "immediatly", "embarassing", "ocassion", "completly". From 8c316a5e9dbe9d1364171a819127e5b47368e747 Mon Sep 17 00:00:00 2001 From: Berserker <47154857+TrinityBerserker@users.noreply.github.com> Date: Sun, 7 Jul 2024 17:03:26 -0600 Subject: [PATCH 18/25] defender archivo Project to have a defender of a file. --- PROGRAMAS DE PYTHON/defenderarchivo.py | 48 ++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 PROGRAMAS DE PYTHON/defenderarchivo.py diff --git a/PROGRAMAS DE PYTHON/defenderarchivo.py b/PROGRAMAS DE PYTHON/defenderarchivo.py new file mode 100644 index 0000000..af18307 --- /dev/null +++ b/PROGRAMAS DE PYTHON/defenderarchivo.py @@ -0,0 +1,48 @@ +import os +import time +import shutil +from watchdog.observers import Observer +from watchdog.events import FileSystemEventHandler + +# Carpeta a monitorear +folder_to_watch = "C:/Users/Username/Desktop/FirewallFolder" + +# Función para verificar si un archivo es sospechoso +def is_suspicious(file_path): + # Implementación básica de detección: solo verifica la extensión + suspicious_extensions = ['.exe', '.bat', '.vbs', '.js'] # Ejemplo de extensiones sospechosas + + _, file_extension = os.path.splitext(file_path) + if file_extension.lower() in suspicious_extensions: + return True + return False + +# Manejador de eventos para el monitor de la carpeta +class FolderMonitor(FileSystemEventHandler): + def on_created(self, event): + if not event.is_directory: + file_path = event.src_path + if is_suspicious(file_path): + print(f"Archivo sospechoso detectado: {file_path}") + # Aquí podrías implementar acciones como mover el archivo a cuarentena + # shutil.move(file_path, "ruta a carpeta de cuarentena") + else: + print(f"Archivo seguro detectado: {file_path}") + +# Función principal para iniciar el monitoreo +def start_firewall(): + event_handler = FolderMonitor() + observer = Observer() + observer.schedule(event_handler, folder_to_watch, recursive=True) + observer.start() + print(f"Monitoreando la carpeta: {folder_to_watch}") + + try: + while True: + time.sleep(1) + except KeyboardInterrupt: + observer.stop() + observer.join() + +if __name__ == "__main__": + start_firewall() From 7fcbcbf952a8752dd34149ea450be4d11c71d7e6 Mon Sep 17 00:00:00 2001 From: Berserker <47154857+TrinityBerserker@users.noreply.github.com> Date: Sun, 7 Jul 2024 17:23:02 -0600 Subject: [PATCH 19/25] Textual Adventure Game: Implement a textual adventure game where players make decisions that affect the course of the story. You can include ASCII graphics to enhance the viewing experience. --- PROGRAMAS DE PYTHON/juegoderol.py | 131 ++++++++++++++++++++++++++++++ 1 file changed, 131 insertions(+) create mode 100644 PROGRAMAS DE PYTHON/juegoderol.py diff --git a/PROGRAMAS DE PYTHON/juegoderol.py b/PROGRAMAS DE PYTHON/juegoderol.py new file mode 100644 index 0000000..d53e95e --- /dev/null +++ b/PROGRAMAS DE PYTHON/juegoderol.py @@ -0,0 +1,131 @@ +def print_welcome_message(): + print(""" + ==================================== + Bienvenido al Juego de Aventura Textual + ==================================== + """) + print(""" + _.--. + _.-'_:-'|| + _.-'_.-::::'|| + _.-:'_.-::::::' || +.'`-.-:::::::' || +/.'`;|:::::::' ||_ +|| ||::::::' _.;._'-._ +|| ||:::::' _.-!oo @.!-._'-. +\\'. ||:::::.-!()oo @!()@.-'_.| +'.'-;|:.-'.&$@.& ()$%-'o.'\\U|| + `>'-.!@%()@'@_%-'_.-o _.|'|| + ||-._'-.@.-'_.-' _.-o |'|| + ||=[ '-._.-\\U/.-' o |'|| + || '-.]=|| |'| o |'|| + || || |'| _| '; + || || |'| _.-'_.-' + |'-._ || |'|_.-'_.-' + '-._'-.|| |' `_.-' + '-.||_/.-' + """) + +def make_choice(prompt, options): + choice = None + while choice not in options: + print(prompt) + for key, value in options.items(): + print(f"{key}: {value}") + choice = input("Elige una opción: ").strip().lower() + return choice + +def cave_adventure(): + print("Te despiertas en una cueva oscura. Hay dos túneles frente a ti.") + choice = make_choice("¿Cuál túnel tomas?", {'a': 'Túnel izquierdo', 'b': 'Túnel derecho'}) + + if choice == 'a': + print("Caminas por el túnel izquierdo y encuentras un cofre.") + choice = make_choice("¿Abres el cofre?", {'a': 'Sí', 'b': 'No'}) + + if choice == 'a': + print("¡Encuentras un tesoro! Sigues adelante y ves una luz al final del túnel.") + forest_adventure() + else: + print("Decides no abrir el cofre y continúas caminando.") + print("Te pierdes en la oscuridad y encuentras una bifurcación.") + choice = make_choice("¿Qué dirección tomas?", {'a': 'Izquierda', 'b': 'Derecha'}) + + if choice == 'a': + print("Encuentras una salida de la cueva, pero estás en un bosque oscuro.") + forest_adventure() + else: + print("Te encuentras con un dragón. Has perdido el juego.") + else: + print("Caminas por el túnel derecho y te encuentras con un dragón.") + choice = make_choice("¿Luchas contra el dragón?", {'a': 'Sí', 'b': 'No'}) + + if choice == 'a': + print("Luchas valientemente, pero el dragón es demasiado fuerte. Has perdido el juego.") + else: + print("Huyes rápidamente y encuentras una salida de la cueva. Has sobrevivido.") + forest_adventure() + +def forest_adventure(): + print("Te encuentras en un bosque denso. Hay un sendero que se divide en dos.") + choice = make_choice("¿Qué camino tomas?", {'a': 'Sendero izquierdo', 'b': 'Sendero derecho'}) + + if choice == 'a': + print("Sigues el sendero izquierdo y encuentras una cabaña.") + choice = make_choice("¿Entras a la cabaña?", {'a': 'Sí', 'b': 'No'}) + + if choice == 'a': + print("Entras a la cabaña y encuentras provisiones. Recuperas fuerzas y decides explorar más.") + mountain_adventure() + else: + print("Decides no entrar a la cabaña y sigues caminando.") + print("Te pierdes en el bosque y nunca encuentras la salida. Has perdido el juego.") + else: + print("Sigues el sendero derecho y encuentras un río.") + river_adventure() + +def river_adventure(): + print("Te encuentras en un río caudaloso. Hay un puente y un bote.") + choice = make_choice("¿Qué decides hacer?", {'a': 'Cruzar el puente', 'b': 'Usar el bote'}) + + if choice == 'a': + print("Cruzas el puente y llegas a una aldea. Los aldeanos te ayudan y finalmente encuentras el camino a casa. ¡Has ganado el juego!") + else: + print("Usas el bote, pero la corriente es muy fuerte y el bote se vuelca. Has perdido el juego.") + +def mountain_adventure(): + print("Te encuentras al pie de una montaña. Hay un sendero empinado y una cueva.") + choice = make_choice("¿Qué decides hacer?", {'a': 'Subir la montaña', 'b': 'Entrar en la cueva'}) + + if choice == 'a': + print("Subes la montaña y encuentras un monasterio. Los monjes te ofrecen refugio y sabiduría.") + choice = make_choice("¿Aceptas quedarte con los monjes?", {'a': 'Sí', 'b': 'No'}) + + if choice == 'a': + print("Aprendes mucho de los monjes y encuentras paz interior. Has encontrado un nuevo hogar. ¡Has ganado el juego!") + else: + print("Decides seguir tu camino y desciendes por el otro lado de la montaña, encontrando una nueva aventura.") + print("Encuentras un valle lleno de vida y decides establecerte allí. ¡Has ganado el juego!") + else: + print("Entras en la cueva y encuentras un lago subterráneo.") + choice = make_choice("¿Nadas a través del lago?", {'a': 'Sí', 'b': 'No'}) + + if choice == 'a': + print("Nadas a través del lago y encuentras una salida secreta. Te lleva a un hermoso jardín.") + choice = make_choice("¿Exploras el jardín?", {'a': 'Sí', 'b': 'No'}) + + if choice == 'a': + print("Exploras el jardín y encuentras una comunidad secreta de sabios. Aprendes de ellos y vives en armonía. ¡Has ganado el juego!") + else: + print("Decides no explorar el jardín y sigues adelante.") + print("Encuentras un desierto y te pierdes en la arena. Has perdido el juego.") + else: + print("Decides no nadar y vuelves al pie de la montaña.") + mountain_adventure() + +def start_adventure(): + print_welcome_message() + cave_adventure() + +if __name__ == "__main__": + start_adventure() From 958b834dbd82ed08a195671c2e5b3ce3fda09fab Mon Sep 17 00:00:00 2001 From: Berserker <47154857+TrinityBerserker@users.noreply.github.com> Date: Wed, 10 Jul 2024 02:30:41 -0600 Subject: [PATCH 20/25] Real Time Network Monitor A tool that captures and analyzes network packets using Scapy. --- .../Monitor de Red en Tiempo Real.py | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 PROGRAMAS DE PYTHON/Monitor de Red en Tiempo Real.py diff --git a/PROGRAMAS DE PYTHON/Monitor de Red en Tiempo Real.py b/PROGRAMAS DE PYTHON/Monitor de Red en Tiempo Real.py new file mode 100644 index 0000000..50360bb --- /dev/null +++ b/PROGRAMAS DE PYTHON/Monitor de Red en Tiempo Real.py @@ -0,0 +1,26 @@ +from scapy.all import sniff, IP, TCP, UDP + +# Función de callback para manejar los paquetes capturados +def packet_callback(packet): + # Si el paquete tiene una capa IP + if IP in packet: + ip_src = packet[IP].src + ip_dst = packet[IP].dst + + # Si el paquete tiene una capa TCP + if TCP in packet: + tcp_sport = packet[TCP].sport + tcp_dport = packet[TCP].dport + print(f"TCP Packet: {ip_src}:{tcp_sport} -> {ip_dst}:{tcp_dport}") + + # Si el paquete tiene una capa UDP + elif UDP in packet: + udp_sport = packet[UDP].sport + udp_dport = packet[UDP].dport + print(f"UDP Packet: {ip_src}:{udp_sport} -> {ip_dst}:{udp_dport}") + + else: + print(f"Other IP Packet: {ip_src} -> {ip_dst}") + +# Captura paquetes en la interfaz especificada (puedes cambiar 'eth0' por la interfaz de tu red) +sniff(prn=packet_callback, filter="ip", iface="eth0", store=0) From 1dff1f694b8dec4dc11ab6c027ca4c7ec392afcf Mon Sep 17 00:00:00 2001 From: Berserker <47154857+TrinityBerserker@users.noreply.github.com> Date: Wed, 10 Jul 2024 02:55:19 -0600 Subject: [PATCH 21/25] A Twitter Bot A Twitter Bot to publish RT and Sputnik News. --- PROGRAMAS DE PYTHON/bottwit.py | 59 ++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 PROGRAMAS DE PYTHON/bottwit.py diff --git a/PROGRAMAS DE PYTHON/bottwit.py b/PROGRAMAS DE PYTHON/bottwit.py new file mode 100644 index 0000000..7f03773 --- /dev/null +++ b/PROGRAMAS DE PYTHON/bottwit.py @@ -0,0 +1,59 @@ +import tweepy +import requests +from bs4 import BeautifulSoup +import time + +# Credenciales de API de Twitter +API_KEY = 'tu_api_key' +API_SECRET_KEY = 'tu_api_secret_key' +ACCESS_TOKEN = 'tu_access_token' +ACCESS_TOKEN_SECRET = 'tu_access_token_secret' + +# Autenticación en Twitter +auth = tweepy.OAuthHandler(API_KEY, API_SECRET_KEY) +auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) +api = tweepy.API(auth) + +# URLs de RT Noticias y Sputnik +rt_url = 'https://www.rt.com/news/ukraine/' +sputnik_url = 'https://sputniknews.com/europe/' + +# Función para obtener noticias +def get_news(url): + response = requests.get(url) + soup = BeautifulSoup(response.content, 'html.parser') + headlines = soup.find_all('h2') + return [headline.get_text() for headline in headlines] + +# Función para hacer tweets sarcásticos +def post_sarcastic_tweet(): + sarcastic_tweets = [ + "Just when you thought things couldn't get more complicated in Ukraine...", + "Another day, another news from Ukraine. What's next?", + "Ukraine update: Because clearly, we needed more drama in the world.", + "Breaking news from Ukraine! Because regular news just isn't dramatic enough." + ] + tweet = random.choice(sarcastic_tweets) + api.update_status(tweet) + +# Función principal +def main(): + while True: + # Obtener y publicar noticias de RT + rt_news = get_news(rt_url) + for news in rt_news[:3]: # Limitar a 3 noticias para no exceder el límite de Twitter + api.update_status(f"RT Noticias: {news} #Ukraine") + + # Obtener y publicar noticias de Sputnik + sputnik_news = get_news(sputnik_url) + for news in sputnik_news[:3]: + api.update_status(f"Sputnik: {news} #Ukraine") + + # Publicar un tweet sarcástico + post_sarcastic_tweet() + + # Esperar 10 minutos + time.sleep(600) + +if __name__ == "__main__": + main() From 42a057c515e9d71f525311399be012e469b125c6 Mon Sep 17 00:00:00 2001 From: Berserker <47154857+TrinityBerserker@users.noreply.github.com> Date: Thu, 11 Jul 2024 05:10:32 -0600 Subject: [PATCH 22/25] SimulationofBruteForceAttack A tool to simulate brute force attacks and evaluate password security. (Any less educational use is the responsibility of the respective user executing it). --- .../SimulationofBruteForceAttack.py | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 PROGRAMAS DE PYTHON/SimulationofBruteForceAttack.py diff --git a/PROGRAMAS DE PYTHON/SimulationofBruteForceAttack.py b/PROGRAMAS DE PYTHON/SimulationofBruteForceAttack.py new file mode 100644 index 0000000..023bd4e --- /dev/null +++ b/PROGRAMAS DE PYTHON/SimulationofBruteForceAttack.py @@ -0,0 +1,43 @@ +import itertools +import string +import time +import sys + +def brute_force_attack(password, charset, time_limit=1200): + start_time = time.time() + attempts = 0 + max_combinations = sum(len(charset) ** length for length in range(1, len(password) + 1)) + + for length in range(1, len(password) + 1): + for guess in itertools.product(charset, repeat=length): + if time.time() - start_time > time_limit: + print("\nTime limit exceeded. Attack interrupted.") + return None + + attempts += 1 + guess = ''.join(guess) + progress = attempts / max_combinations * 100 + sys.stdout.write(f"\rProgress: [{int(progress)}%] {guess}") + sys.stdout.flush() + + if guess == password: + end_time = time.time() + return (guess, attempts, end_time - start_time) + + return None + +def main(): + password = input("Enter the password to test: ") + charset = string.ascii_letters + string.digits + string.punctuation + + print(f"Starting brute force attack on password: {password}") + result = brute_force_attack(password, charset) + + if result: + guess, attempts, duration = result + print(f"\nPassword '{password}' cracked in {attempts} attempts and {duration:.2f} seconds.") + else: + print("\nFailed to crack the password.") + +if __name__ == "__main__": + main() From bb53a88211d2d3fe0b0411321e62bd1da230ed1b Mon Sep 17 00:00:00 2001 From: Berserker <47154857+TrinityBerserker@users.noreply.github.com> Date: Thu, 11 Jul 2024 05:17:26 -0600 Subject: [PATCH 23/25] ASCIIArtGeneratorinPython ASCII Art Generator: Convert images into ASCII art. --- .../ASCIIArtGeneratorinPython.py | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 PROGRAMAS DE PYTHON/ASCIIArtGeneratorinPython.py diff --git a/PROGRAMAS DE PYTHON/ASCIIArtGeneratorinPython.py b/PROGRAMAS DE PYTHON/ASCIIArtGeneratorinPython.py new file mode 100644 index 0000000..ed8a5c3 --- /dev/null +++ b/PROGRAMAS DE PYTHON/ASCIIArtGeneratorinPython.py @@ -0,0 +1,57 @@ +from PIL import Image + +# Definimos una lista de caracteres ASCII que utilizaremos para el arte +ASCII_CHARS = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."] + +# Cambia el tamaño de la imagen +def resize_image(image, new_width=100): + width, height = image.size + ratio = height / width + new_height = int(new_width * ratio) + resized_image = image.resize((new_width, new_height)) + return resized_image + +# Convierte la imagen a escala de grises +def grayify(image): + grayscale_image = image.convert("L") + return grayscale_image + +# Convierte cada píxel a un carácter ASCII +def pixels_to_ascii(image): + pixels = image.getdata() + ascii_str = "" + for pixel in pixels: + ascii_str += ASCII_CHARS[pixel // 25] + return ascii_str + +# Función principal para convertir una imagen a arte ASCII +def image_to_ascii(image_path, new_width=100): + try: + image = Image.open(image_path) + except Exception as e: + print(f"Unable to open image file {image_path}. {e}") + return + + image = resize_image(image, new_width) + image = grayify(image) + + ascii_str = pixels_to_ascii(image) + img_width = image.width + ascii_str_len = len(ascii_str) + ascii_img = "" + + # Dividir el string de caracteres ASCII en líneas para que se ajuste al ancho de la imagen + for i in range(0, ascii_str_len, img_width): + ascii_img += ascii_str[i:i+img_width] + "\n" + + return ascii_img + +# Función para mostrar el arte ASCII en la consola +def main(): + image_path = input("Enter the path to the image file: ") + ascii_art = image_to_ascii(image_path) + if ascii_art: + print(ascii_art) + +if __name__ == "__main__": + main() From ba4a88803fc1ad983046f45444c6f1833f913a6b Mon Sep 17 00:00:00 2001 From: Berserker <47154857+TrinityBerserker@users.noreply.github.com> Date: Sat, 13 Jul 2024 03:31:42 -0600 Subject: [PATCH 24/25] Neuronal Network & Anti-fraud --- .../Red_neuronal_aprendizaje.py | 44 +++++++++++++++++++ PROGRAMAS DE PYTHON/antifraudes.py | 41 +++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 PROGRAMAS DE PYTHON/Red_neuronal_aprendizaje.py create mode 100644 PROGRAMAS DE PYTHON/antifraudes.py diff --git a/PROGRAMAS DE PYTHON/Red_neuronal_aprendizaje.py b/PROGRAMAS DE PYTHON/Red_neuronal_aprendizaje.py new file mode 100644 index 0000000..cf12b90 --- /dev/null +++ b/PROGRAMAS DE PYTHON/Red_neuronal_aprendizaje.py @@ -0,0 +1,44 @@ +import tensorflow as tf +from tensorflow.keras import layers, models +import matplotlib.pyplot as plt + +# Cargar el dataset de MNIST +(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data() + +# Normalizar las imágenes +train_images = train_images / 255.0 +test_images = test_images / 255.0 + +# Construir el modelo +model = models.Sequential([ + layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)), + layers.MaxPooling2D((2, 2)), + layers.Conv2D(64, (3, 3), activation='relu'), + layers.MaxPooling2D((2, 2)), + layers.Conv2D(64, (3, 3), activation='relu'), + layers.Flatten(), + layers.Dense(64, activation='relu'), + layers.Dense(10, activation='softmax') +]) + +# Compilar el modelo +model.compile(optimizer='adam', + loss='sparse_categorical_crossentropy', + metrics=['accuracy']) + +# Entrenar el modelo +history = model.fit(train_images, train_labels, epochs=5, + validation_data=(test_images, test_labels)) + +# Evaluar el modelo +test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) +print(f'\nTest accuracy: {test_acc}') + +# Graficar el rendimiento del entrenamiento y la validación +plt.plot(history.history['accuracy'], label='accuracy') +plt.plot(history.history['val_accuracy'], label = 'val_accuracy') +plt.xlabel('Epoch') +plt.ylabel('Accuracy') +plt.ylim([0.8, 1]) +plt.legend(loc='lower right') +plt.show() diff --git a/PROGRAMAS DE PYTHON/antifraudes.py b/PROGRAMAS DE PYTHON/antifraudes.py new file mode 100644 index 0000000..350604c --- /dev/null +++ b/PROGRAMAS DE PYTHON/antifraudes.py @@ -0,0 +1,41 @@ +import pandas as pd +import numpy as np +from sklearn.model_selection import train_test_split +from sklearn.preprocessing import StandardScaler +from sklearn.ensemble import RandomForestClassifier +from sklearn.metrics import classification_report, confusion_matrix + +# Cargar datos +data = pd.read_csv('creditcard.csv') + +# Exploración básica de datos +print(data.head()) +print(data.info()) +print(data['Class'].value_counts()) + +# Separar características y la variable objetivo +X = data.drop('Class', axis=1) +y = data['Class'] + +# Dividir los datos en conjuntos de entrenamiento y prueba +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) + +# Estandarizar los datos +scaler = StandardScaler() +X_train = scaler.fit_transform(X_train) +X_test = scaler.transform(X_test) + +# Crear y entrenar el modelo +model = RandomForestClassifier(n_estimators=100, random_state=42) +model.fit(X_train, y_train) + +# Realizar predicciones +y_pred = model.predict(X_test) + +# Evaluar el modelo +print(confusion_matrix(y_test, y_pred)) +print(classification_report(y_test, y_pred)) + +# Guardar el modelo entrenado +import joblib +joblib.dump(model, 'fraud_detector_model.pkl') From eead64077eb124c4e2d7ef9a8333450f02dc1fe4 Mon Sep 17 00:00:00 2001 From: "[T5T]Berserker" <47154857+TrinityBerserker@users.noreply.github.com> Date: Mon, 15 Jul 2024 11:13:00 -0600 Subject: [PATCH 25/25] Reminder A program that sends reminders of tasks to be completed at regular intervals. --- PROGRAMAS DE PYTHON/recordardora.py | 44 +++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 PROGRAMAS DE PYTHON/recordardora.py diff --git a/PROGRAMAS DE PYTHON/recordardora.py b/PROGRAMAS DE PYTHON/recordardora.py new file mode 100644 index 0000000..91f86da --- /dev/null +++ b/PROGRAMAS DE PYTHON/recordardora.py @@ -0,0 +1,44 @@ +import schedule +import time +import smtplib +from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText + +# Configuración del correo electrónico +def send_email(subject, body): + # Configura los detalles de tu servidor de correo electrónico + from_email = 'tu_correo@gmail.com' + from_password = 'tu_contraseña' + to_email = 'destinatario@gmail.com' + + msg = MIMEMultipart() + msg['From'] = from_email + msg['To'] = to_email + msg['Subject'] = subject + + msg.attach(MIMEText(body, 'plain')) + + try: + server = smtplib.SMTP('smtp.gmail.com', 587) + server.starttls() + server.login(from_email, from_password) + text = msg.as_string() + server.sendmail(from_email, to_email, text) + server.quit() + print("Email sent successfully") + except Exception as e: + print(f"Failed to send email: {str(e)}") + +# Función para enviar recordatorio +def send_task_reminder(): + subject = "Recordatorio de Tarea" + body = "Recuerda completar tus tareas!" + send_email(subject, body) + +# Programar el recordatorio para cada hora +schedule.every().hour.do(send_task_reminder) + +# Bucle principal para ejecutar las tareas programadas +while True: + schedule.run_pending() + time.sleep(1)