Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
105c7ff
Update README.md
TrinityBerserker Oct 12, 2023
c543bfa
Create python-publish.yml
TrinityBerserker Oct 12, 2023
44c0004
5 more programs done in 1 week.
TrinityBerserker Nov 12, 2023
125b734
Updating my Python programs.
TrinityBerserker Apr 10, 2024
1ba60a9
Merge pull request #3 from PaganoBerserker/main
TrinityBerserker Apr 10, 2024
b3e8e29
IPTables 1
TrinityBerserker Apr 10, 2024
b4ce6cf
Allow SSH Traffic (Port 22)
TrinityBerserker Apr 10, 2024
92c6a9a
Configure Rules Based on Specific Packages
TrinityBerserker Apr 10, 2024
dcf25bc
Species Classifier
TrinityBerserker Apr 11, 2024
0424b5e
Generate a new 2048-bit RSA key
TrinityBerserker Apr 12, 2024
e0428b0
Random Forest
TrinityBerserker Apr 13, 2024
bc9d937
vulnerability analyst
TrinityBerserker Apr 15, 2024
fd22726
vulnerability analyst
TrinityBerserker Apr 15, 2024
d06dc76
vulnerability analyst
TrinityBerserker Apr 15, 2024
655e103
vulneravility analyst
TrinityBerserker Apr 15, 2024
b21cef9
Vulnerality Analyst 6
TrinityBerserker Apr 15, 2024
1a97a0c
A file computer
TrinityBerserker Jul 3, 2024
0cdb735
Automatic word corrector.
TrinityBerserker Jul 3, 2024
8c316a5
defender archivo
TrinityBerserker Jul 7, 2024
7fcbcbf
Textual Adventure Game:
TrinityBerserker Jul 7, 2024
958b834
Real Time Network Monitor
TrinityBerserker Jul 10, 2024
1dff1f6
A Twitter Bot
TrinityBerserker Jul 10, 2024
42a057c
SimulationofBruteForceAttack
TrinityBerserker Jul 11, 2024
bb53a88
ASCIIArtGeneratorinPython
TrinityBerserker Jul 11, 2024
ba4a888
Neuronal Network & Anti-fraud
TrinityBerserker Jul 13, 2024
eead640
Reminder
TrinityBerserker Jul 15, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions .github/workflows/python-publish.yml
Original file line number Diff line number Diff line change
@@ -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 }}
57 changes: 57 additions & 0 deletions PROGRAMAS DE PYTHON/ASCIIArtGeneratorinPython.py
Original file line number Diff line number Diff line change
@@ -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()
40 changes: 40 additions & 0 deletions PROGRAMAS DE PYTHON/Automata1.py
Original file line number Diff line number Diff line change
@@ -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.')
35 changes: 35 additions & 0 deletions PROGRAMAS DE PYTHON/Automata2.py
Original file line number Diff line number Diff line change
@@ -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.')

7 changes: 7 additions & 0 deletions PROGRAMAS DE PYTHON/Funcion.py
Original file line number Diff line number Diff line change
@@ -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)
98 changes: 98 additions & 0 deletions PROGRAMAS DE PYTHON/Hash.py
Original file line number Diff line number Diff line change
@@ -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)
17 changes: 17 additions & 0 deletions PROGRAMAS DE PYTHON/IPTables1.py
Original file line number Diff line number Diff line change
@@ -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)
7 changes: 7 additions & 0 deletions PROGRAMAS DE PYTHON/IPTables2.py
Original file line number Diff line number Diff line change
@@ -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()
8 changes: 8 additions & 0 deletions PROGRAMAS DE PYTHON/IPTables3.py
Original file line number Diff line number Diff line change
@@ -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")

24 changes: 24 additions & 0 deletions PROGRAMAS DE PYTHON/Lista.py
Original file line number Diff line number Diff line change
@@ -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'.")
31 changes: 31 additions & 0 deletions PROGRAMAS DE PYTHON/ML1.py
Original file line number Diff line number Diff line change
@@ -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
Loading