commit 846c54b439acdde4629aaf8470c2da3e133333ba Author: juanjo Date: Fri Oct 27 11:32:40 2023 +0200 Código fuente Python PSP diff --git a/01.Procesos/P1-11-EjecucionAsincrono.py b/01.Procesos/P1-11-EjecucionAsincrono.py new file mode 100644 index 0000000..2dc9302 --- /dev/null +++ b/01.Procesos/P1-11-EjecucionAsincrono.py @@ -0,0 +1,26 @@ +from os import system +import subprocess +import asyncio + +def showNotepad1(): + try: + subprocess.run(['Notepad.exe',]) + except subprocess.CalledProcessError as e: + print(e.output) +async def showNotepad2(): + try: + await asyncio.create_subprocess_exec('notepad.exe') + except subprocess.CalledProcessError as e: + print(e.output) + +async def main(): + print ("inicio llamada síncrona") + showNotepad1() + print ("fin llamada síncrona") + print ("inicio llamada asíncrona") + await showNotepad2() + print ("fin llamada asíncrona") + print("pulsa una tecla para terminar") + system ('Pause') + +asyncio.run(main()) \ No newline at end of file diff --git a/01.Procesos/P1-12-ObtenrerLIstadoDir.py b/01.Procesos/P1-12-ObtenrerLIstadoDir.py new file mode 100644 index 0000000..98f46b3 --- /dev/null +++ b/01.Procesos/P1-12-ObtenrerLIstadoDir.py @@ -0,0 +1,10 @@ +import subprocess + +p1 = subprocess.Popen('dir', shell=True, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + +while True: + line = p1.stdout.readline() + if not line: + break + #the real code does filtering here + print (line.rstrip()) diff --git a/01.Procesos/P1-13-ComunicacionProceso.py b/01.Procesos/P1-13-ComunicacionProceso.py new file mode 100644 index 0000000..b6dbefc --- /dev/null +++ b/01.Procesos/P1-13-ComunicacionProceso.py @@ -0,0 +1,15 @@ +import subprocess + +p1 = subprocess.Popen('ftp', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) +comandos = [b"verbose\n", + b"open test.rebex.net\n", + b"demo\n", + b"password\n", + b"ls\n", + b"get readme.txt\n"] + +for cmd in comandos: + p1.stdin.write (cmd) + +respuesta = p1.communicate(timeout=5)[0] +print (respuesta.decode("cp850", "ignore")) diff --git a/01.Procesos/P1-14-ComunicacionPortapapeles.py b/01.Procesos/P1-14-ComunicacionPortapapeles.py new file mode 100644 index 0000000..a5239a7 --- /dev/null +++ b/01.Procesos/P1-14-ComunicacionPortapapeles.py @@ -0,0 +1,14 @@ +#instalar previamente: "pip install pywin32" +import win32clipboard + +#enviar datos al portapapeles +win32clipboard.OpenClipboard() +win32clipboard.EmptyClipboard() +win32clipboard.SetClipboardText("MARCOMBO") +win32clipboard.CloseClipboard() + +# obtener datos del portapapeles +win32clipboard.OpenClipboard() +datos = win32clipboard.GetClipboardData() +win32clipboard.CloseClipboard() +print (datos) diff --git a/01.Procesos/P1.01-Fork.py b/01.Procesos/P1.01-Fork.py new file mode 100644 index 0000000..2ec4379 --- /dev/null +++ b/01.Procesos/P1.01-Fork.py @@ -0,0 +1,21 @@ +# fork solo funciona en unix/macos +import os + + +def padre(): + while True: + newpid = os.fork() + if newpid == 0: + hijo() + else: + pids = (os.getpid(), newpid) + print("Padre: %d, Hijo: %d\n" % pids) + reply = input("Pulsa 's' si quieres crear un nuevo proceso") + if reply != 's': + break + +def hijo(): + print('\n>>>>>>>>>> Nuevo hijo creado con el pid %d a punto de finalizar<<<<<' % os.getpid()) + os._exit(0) + +padre() \ No newline at end of file diff --git a/01.Procesos/P1.02-likefork-win.py b/01.Procesos/P1.02-likefork-win.py new file mode 100644 index 0000000..72cab95 --- /dev/null +++ b/01.Procesos/P1.02-likefork-win.py @@ -0,0 +1,18 @@ +from multiprocessing import Process +import os + +def hijo(): + print("Padre: %d, Hijo: %d\n" % ( os.getppid(),os.getpid())) + os._exit(0) + +def padre(): + while True: + p = Process(target=hijo) + p.start() + print ("\nNuevo hijo creado " , p.pid) + p.join() + reply = input("Pulsa 's' si quieres crear un nuevo proceso\n") + if reply != 's': + break +if __name__ == '__main__': + padre() \ No newline at end of file diff --git a/01.Procesos/P1.03-Lanza-notepad.py b/01.Procesos/P1.03-Lanza-notepad.py new file mode 100644 index 0000000..9eb3a4a --- /dev/null +++ b/01.Procesos/P1.03-Lanza-notepad.py @@ -0,0 +1,7 @@ +import subprocess +try: + subprocess.run(['Notepad.exe',]) + subprocess.run(['c:/windows/notepad.exe',]) + subprocess.run(['Notepad.exe','texto.txt']) +except subprocess.CalledProcessError as e: + print(e.output) \ No newline at end of file diff --git a/01.Procesos/P1.04-proceso-parametros.py b/01.Procesos/P1.04-proceso-parametros.py new file mode 100644 index 0000000..dea07be --- /dev/null +++ b/01.Procesos/P1.04-proceso-parametros.py @@ -0,0 +1,8 @@ +import subprocess + +try: + subprocess.run(["ping", "www.marcombo.com","-n","5"]) + #en linux + #subprocess.run(["ping", "www.marcombo.com","-c","5"]) +except subprocess.CalledProcessError as e: + print(e.output) \ No newline at end of file diff --git a/01.Procesos/P1.05-proceso-entorno.py b/01.Procesos/P1.05-proceso-entorno.py new file mode 100644 index 0000000..e8c3565 --- /dev/null +++ b/01.Procesos/P1.05-proceso-entorno.py @@ -0,0 +1,14 @@ +import subprocess + +def iniciaPrograma(): + try: + SW_SHOWMAXIMIZED = 3 + info = subprocess.STARTUPINFO() + info.dwFlags |= subprocess.STARTF_USESHOWWINDOW + info.wShowWindow = SW_SHOWMAXIMIZED + subprocess.Popen('Notepad.exe', startupinfo=info) + except subprocess.CalledProcessError as e: + print(e.output) +iniciaPrograma() +input("Pulsa una tecla para terminar la ejecución") + diff --git a/01.Procesos/P1.06-proceso-referencia.py b/01.Procesos/P1.06-proceso-referencia.py new file mode 100644 index 0000000..b484e2e --- /dev/null +++ b/01.Procesos/P1.06-proceso-referencia.py @@ -0,0 +1,17 @@ +import subprocess +import time + +def CrearProceso(): + try: + SW_SHOWMAXIMIZED = 3 + info = subprocess.STARTUPINFO() + info.dwFlags |= subprocess.STARTF_USESHOWWINDOW + info.wShowWindow = SW_SHOWMAXIMIZED + proc = subprocess.Popen('notepad.exe', startupinfo=info) + return proc + except subprocess.CalledProcessError as e: + print(e.output) +p = CrearProceso() +print ("El PID de este proceso es: " + str(p.pid)) +time.sleep(5) + diff --git a/01.Procesos/P1.07-Listado-procesos-sistema.py b/01.Procesos/P1.07-Listado-procesos-sistema.py new file mode 100644 index 0000000..aef2e5c --- /dev/null +++ b/01.Procesos/P1.07-Listado-procesos-sistema.py @@ -0,0 +1,12 @@ +#instalar psutil: pip install psutil +import psutil + +try: + for proc in psutil.process_iter(): + #Obtener el nombre y el PID de cada proceso + processName = proc.name() + processID = proc.pid + print(processName , ' ::: ', processID) +#except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess) as e: +except: + print("error") \ No newline at end of file diff --git a/01.Procesos/P1.08-Listado-procesos-sistema-win-wmic.py b/01.Procesos/P1.08-Listado-procesos-sistema-win-wmic.py new file mode 100644 index 0000000..260c472 --- /dev/null +++ b/01.Procesos/P1.08-Listado-procesos-sistema-win-wmic.py @@ -0,0 +1,10 @@ +import subprocess + +# obtención de los procesos +Datos = subprocess.check_output(['wmic', 'process', 'list', 'brief']) +a = str(Datos) +try: + for i in range(len(a)): + print(a.split("\\r\\r\\n")[i]) +except IndexError as e: + print("Finalizado") diff --git a/01.Procesos/P1.09-Acceso-propiedades-proceso.py b/01.Procesos/P1.09-Acceso-propiedades-proceso.py new file mode 100644 index 0000000..2436174 --- /dev/null +++ b/01.Procesos/P1.09-Acceso-propiedades-proceso.py @@ -0,0 +1,27 @@ +import psutil +import os +import subprocess +import sys + +def ProcesoActual (): + return psutil.Process(os.getpid()) + +def esWindows(): + try: + sys.getwindowsversion() + except AttributeError: + return (False) + else: + return (True) + +print (ProcesoActual().name()) #nombre +print (ProcesoActual().cwd()) #path de ejecución +#prioridad ante del cambio +print (ProcesoActual().nice()) +if esWindows(): + subprocess.check_output("wmic process where processid=\""+str(os.getpid())+"\" CALL setpriority \"below normal\"") +else: + os.nice(1) +#prioridad después del cambio +print (ProcesoActual().nice()) +a = input() \ No newline at end of file diff --git a/01.Procesos/P1.10-Eliminacion-procesos.py b/01.Procesos/P1.10-Eliminacion-procesos.py new file mode 100644 index 0000000..2d3d3db --- /dev/null +++ b/01.Procesos/P1.10-Eliminacion-procesos.py @@ -0,0 +1,13 @@ +import psutil + +for proc in psutil.process_iter(): + try: + # Obtener el nombre del proceso + nombreProceso = proc.name() + if proc.name() == "notepad.exe": + PID = proc.pid + print("Eliminando el proceso: ", nombreProceso , ' ::: ', PID) + proc.kill() + except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): + print ("error") + diff --git a/01.Procesos/algo.txt b/01.Procesos/algo.txt new file mode 100644 index 0000000..7284ab4 --- /dev/null +++ b/01.Procesos/algo.txt @@ -0,0 +1 @@ +aaaa \ No newline at end of file diff --git a/02.Threads/P2.01-HelloThread.py b/02.Threads/P2.01-HelloThread.py new file mode 100644 index 0000000..40b7c77 --- /dev/null +++ b/02.Threads/P2.01-HelloThread.py @@ -0,0 +1,9 @@ +import threading + +#método al que se va a aosciar el hilo +def Saludo(): + print ('hola') + +t = threading.Thread(target=Saludo) +t.start() +print ("hola") #impresión en el hilo principal \ No newline at end of file diff --git a/02.Threads/P2.02-MultiplesHIlos.py b/02.Threads/P2.02-MultiplesHIlos.py new file mode 100644 index 0000000..34041f9 --- /dev/null +++ b/02.Threads/P2.02-MultiplesHIlos.py @@ -0,0 +1,13 @@ +import threading + +def actividad(): + print ("Escribo desde un hilo") + return + +print ("INICIO") +hilos = list() +for i in range(50): + t = threading.Thread(target=actividad) + hilos.append(t) + t.start() +print ("ESCRIBO EN PRINCIPAL") diff --git a/02.Threads/P2.03-Alternancia.py b/02.Threads/P2.03-Alternancia.py new file mode 100644 index 0000000..1643ddf --- /dev/null +++ b/02.Threads/P2.03-Alternancia.py @@ -0,0 +1,13 @@ +import threading + +def escribeY(): + for i in range(1000): + print ("y", end="") + return + +print ("INICIO") +t = threading.Thread(target=escribeY) +t.start() + +for i in range(1000): + print ("X", end="") \ No newline at end of file diff --git a/02.Threads/P2.04-AccesoDatosComunes.py b/02.Threads/P2.04-AccesoDatosComunes.py new file mode 100644 index 0000000..90231c7 --- /dev/null +++ b/02.Threads/P2.04-AccesoDatosComunes.py @@ -0,0 +1,17 @@ +import threading +import time +import random + +def tareaUno(): + global Realizado + #time.sleep (random.random()) + if not Realizado: + print("Tarea realizada") + Realizado = True + return + +Realizado = False +t = threading.Thread(target=tareaUno) +t.start() +tareaUno() +time.sleep(1) diff --git a/02.Threads/P2.04b-AccesoDatosComunesMuchosHilos.py b/02.Threads/P2.04b-AccesoDatosComunesMuchosHilos.py new file mode 100644 index 0000000..dbf08b8 --- /dev/null +++ b/02.Threads/P2.04b-AccesoDatosComunesMuchosHilos.py @@ -0,0 +1,22 @@ +import threading +import time +import random + +def tareaUno(): + global Done + #time.sleep (random.random()) + if not Done: + print("Tarea realizada") + Done = True + else : + print ("tarea NO REALIZADA") + return + +Done = False +hilos = list() +for i in range(50): + t = threading.Thread(target=tareaUno) + hilos.append(t) + t.start() +tareaUno() +time.sleep(1) \ No newline at end of file diff --git a/02.Threads/P2.05-PasarDatos.py b/02.Threads/P2.05-PasarDatos.py new file mode 100644 index 0000000..f039bdb --- /dev/null +++ b/02.Threads/P2.05-PasarDatos.py @@ -0,0 +1,14 @@ +import logging +import threading +import time + +def thread_Apellido(name): + print (name + " Rodríguez") + #print (name + " Rodríguez\n") + +nombres = ["Julio", "Javier", "Eladio", "Jose", "Manuel"] +hilos = list() +for n in nombres: + t = threading.Thread(target=thread_Apellido, args=(n,)) + hilos.append(t) + t.start() \ No newline at end of file diff --git a/02.Threads/P2.06-PasarDatosDict.py b/02.Threads/P2.06-PasarDatosDict.py new file mode 100644 index 0000000..6ac6530 --- /dev/null +++ b/02.Threads/P2.06-PasarDatosDict.py @@ -0,0 +1,15 @@ +import logging +import threading +import time + +def thread_Apellido(name, inicio=1, fin=1): + for x in range(inicio, fin): + print (f"{name} Rodríguez {str(x)} años\n",end="") + + +nombres = ["Julio", "Javier", "Eladio", "Jose", "Manuel"] +hilos = list() +for n in nombres: + t = threading.Thread(target=thread_Apellido, args=(n,), kwargs={'inicio':5, 'fin':8}) + hilos.append(t) + t.start() \ No newline at end of file diff --git a/02.Threads/P2.07-LocalSotrage.py b/02.Threads/P2.07-LocalSotrage.py new file mode 100644 index 0000000..dd23828 --- /dev/null +++ b/02.Threads/P2.07-LocalSotrage.py @@ -0,0 +1,24 @@ +import threading +import random + +def mostrar(d): + try: + val = d.valor + except AttributeError: + print(f"{threading.current_thread().name}: Aún no inicializado\n", end="") + else: + print(f"{threading.current_thread().name}: {val}\n", end="") + +def hilo(dato): + mostrar(dato) + dato.valor = random.randint(1, 100) + mostrar(dato) + +dato = threading.local() #variable con instancia local en cada hilo +mostrar(dato) +dato.valor = 999 +mostrar(dato) + +for i in range(3): + t = threading.Thread(target=hilo, args=(dato,)) + t.start() \ No newline at end of file diff --git a/02.Threads/P2.08-Propiedades.py b/02.Threads/P2.08-Propiedades.py new file mode 100644 index 0000000..4036712 --- /dev/null +++ b/02.Threads/P2.08-Propiedades.py @@ -0,0 +1,16 @@ +import threading + +def Funcion_hilo(): + if (threading.current_thread().name == "miHilo7"): + threading.current_thread().name = "nombre-cambiado" + print (f"Hola desde: {threading.current_thread().name} \ + ID {threading.current_thread().ident}\n", end="") + #threading.current_thread().ident = 666 #comprobaicón error + +hilos = list() +for n in range(1,11): + t = threading.Thread(target=Funcion_hilo, name = "miHilo") + if (n>5): + t.name = "miHilo"+str (n) + hilos.append(t) + t.start() \ No newline at end of file diff --git a/02.Threads/P2.09-ListarProcesos.py b/02.Threads/P2.09-ListarProcesos.py new file mode 100644 index 0000000..b2f8926 --- /dev/null +++ b/02.Threads/P2.09-ListarProcesos.py @@ -0,0 +1,13 @@ +import threading +import time + +def tarea(): + time.sleep(1) + return + +for _ in range(10): + threading.Thread(target=tarea).start() + +print ("Hilos activos: ",threading.active_count()) +for thread in threading.enumerate(): + print(thread.name) \ No newline at end of file diff --git a/02.Threads/P2.10-daemon-falso.py b/02.Threads/P2.10-daemon-falso.py new file mode 100644 index 0000000..b201e02 --- /dev/null +++ b/02.Threads/P2.10-daemon-falso.py @@ -0,0 +1,13 @@ +from threading import * +import time + +def hilo(): + for i in range(10): + print('Hilo no Daemon (Foregoround)') + time.sleep(1) + +t = Thread(target=hilo) +t.start() + +time.sleep(5) +print('Hilo principal') \ No newline at end of file diff --git a/02.Threads/P2.11-daemon-true.py b/02.Threads/P2.11-daemon-true.py new file mode 100644 index 0000000..29f2ada --- /dev/null +++ b/02.Threads/P2.11-daemon-true.py @@ -0,0 +1,14 @@ +from threading import * +import time + +def hilo(): + for i in range(10): + print('Hilo no Daemon (Backgoround)') + time.sleep(1) + +t = Thread(target=hilo) +t.daemon = True +t.start() + +time.sleep(5) +print('Hilo principal') \ No newline at end of file diff --git a/02.Threads/P2.12-FinPostergado.py b/02.Threads/P2.12-FinPostergado.py new file mode 100644 index 0000000..409dd4b --- /dev/null +++ b/02.Threads/P2.12-FinPostergado.py @@ -0,0 +1,10 @@ +from threading import * +import time + +def hilo(): + #time.sleep(1) + print("Hola") + +T = Thread(target = hilo) +T.daemon=True +T.start() diff --git a/02.Threads/P2.13-ThreadDentroClase.py b/02.Threads/P2.13-ThreadDentroClase.py new file mode 100644 index 0000000..c6d9a74 --- /dev/null +++ b/02.Threads/P2.13-ThreadDentroClase.py @@ -0,0 +1,23 @@ +import threading + +class miHilo(threading.Thread): + def __init__(self, num): + super(miHilo, self).__init__() + self.numero = num + self.nombre = "" + def run(self): + if self.nombre == "hiloPar": + print (f'par: {self.numero}\n',end='') + else: + print (f'impar: {self.numero}\n',end='') + +ListaHilos = [] #inicio con la lista vacía +for i in range(4): + t = miHilo(i) + if (i % 2) == 0: + t.nombre = "hiloPar" + else: + t.nombre = "hiloImpar" + ListaHilos.append(t) +for h in ListaHilos: + h.start() \ No newline at end of file diff --git a/02.Threads/P2.14-CambiarDatosEnEjecucion.py b/02.Threads/P2.14-CambiarDatosEnEjecucion.py new file mode 100644 index 0000000..2e820a9 --- /dev/null +++ b/02.Threads/P2.14-CambiarDatosEnEjecucion.py @@ -0,0 +1,24 @@ +from threading import Thread +import time +import logging + +logging.basicConfig( level=logging.DEBUG, + format='[%(threadName)-10s]: %(message)s') + +class miHilo(Thread): + def __init__(self): + super(miHilo, self).__init__() + self.nombre= "" + def run(self): + for i in range (20): + #print (self.nombre) + logging.debug ("iteración %i, nombre: %s", i+1,self.nombre) + time.sleep (0.1) + +t = miHilo() +t.nombre ="Pepe" +t.start() +time.sleep(0.5) +#modificamos un dato posteriormente a inicializarse el hilo +t.dato ="Lola" + \ No newline at end of file diff --git a/02.Threads/P2.15-Join.py b/02.Threads/P2.15-Join.py new file mode 100644 index 0000000..332e9a9 --- /dev/null +++ b/02.Threads/P2.15-Join.py @@ -0,0 +1,25 @@ +import threading +import logging + +logging.basicConfig( level=logging.DEBUG, + format='[%(threadName)-10s]: %(message)s') + +def imprime_x(x, n): + logging.debug("INICIO") + for i in range(n): + logging.debug (x) + logging.debug("FIN") + +t1 = threading.Thread(target=imprime_x, args=("norte", 5,)) +t2 = threading.Thread(target=imprime_x, args=("sur", 10,)) + +t1.start() +t2.start() + +# espera hasta que el hilo t1 hay finalizado +t1.join() +# espera hasta que el hilo t2 hay finalizado +t2.join() + +#llega hasta aquí cuando los dos hilos han +logging.debug("Fin!") \ No newline at end of file diff --git a/02.Threads/P2.16-Acceso_concurrente.py b/02.Threads/P2.16-Acceso_concurrente.py new file mode 100644 index 0000000..fe3ce22 --- /dev/null +++ b/02.Threads/P2.16-Acceso_concurrente.py @@ -0,0 +1,25 @@ +from threading import Lock, Thread +import time + +def suma_uno(): + global g + a = g + time.sleep(0.001) + g = a+1 + +def suma_tres(): + global g + a = g + time.sleep(0.001) + g =a+3 + +g = 0 +threads = [] +for func in [suma_uno,suma_tres]: + threads.append(Thread(target=func)) + threads[-1].start() + +for thread in threads: + thread.join() + +print(g) diff --git a/02.Threads/P2.16a-Acceso_concurrente_Lock.py b/02.Threads/P2.16a-Acceso_concurrente_Lock.py new file mode 100644 index 0000000..0edac28 --- /dev/null +++ b/02.Threads/P2.16a-Acceso_concurrente_Lock.py @@ -0,0 +1,30 @@ +from threading import Lock, Thread +import time + +def suma_uno(): + global g + lock.acquire() + a = g + time.sleep(0.001) + g = a+1 + lock.release() + +def suma_tres(): + global g + with lock: + a = g + time.sleep(0.001) + g =a+3 + +lock = Lock() +g = 0 +threads = [] + +for func in [suma_uno,suma_tres]: + threads.append(Thread(target=func)) + threads[-1].start() + +for thread in threads: + thread.join() + +print(g) diff --git a/02.Threads/P2.17-Lock_como_parametro.py b/02.Threads/P2.17-Lock_como_parametro.py new file mode 100644 index 0000000..7ad68d4 --- /dev/null +++ b/02.Threads/P2.17-Lock_como_parametro.py @@ -0,0 +1,27 @@ +import threading +from time import time + +def f_hilo(lock): + global x + for _ in range(1000000): + #lock.acquire() + for _ in range(100): + a=x + x=a+1 + #lock.release() + +x = 0 +#tiempo_inicial = time() +lock = threading.Lock() + +t1 = threading.Thread(target=f_hilo, args=(lock,)) +t2 = threading.Thread(target=f_hilo, args=(lock,)) + +t1.start() +t2.start() + +t1.join() +t2.join() + +#print (time()-tiempo_inicial) +print (x) diff --git a/02.Threads/P2.18-LockCuentas.py b/02.Threads/P2.18-LockCuentas.py new file mode 100644 index 0000000..508e45d --- /dev/null +++ b/02.Threads/P2.18-LockCuentas.py @@ -0,0 +1,55 @@ + +import threading +import time + +class CuentaBancaria: + def __init__(self, nombre, saldo): + self.nombre = nombre + self.saldo = saldo + + def __str__(self): + return self.nombre+' '+str(self.saldo) + +class BankTransferThread(threading.Thread): + def __init__(self, ordenante, receptor, cantidad): + threading.Thread.__init__(self) + self.ordenante = ordenante + self.receptor = receptor + self.cantidad = cantidad + + def run(self): + lock.acquire() + + saldo_ordenante= self.ordenante.saldo + saldo_ordenante-= self.cantidad + # retraso para permitir ejecutar saltar entre hilos + time.sleep(0.001) + self.ordenante.saldo = saldo_ordenante + + saldo_receptor = self.receptor.saldo + saldo_receptor += self.cantidad + # retraso para permitir ejecutar saltar entre hilos + time.sleep(0.001) + self.receptor.saldo = saldo_receptor + + lock.release() + + +# Las cuentas son recursos compartidos +cuenta1 = CuentaBancaria("cuentaOrigen", 100) +cuenta2 = CuentaBancaria("cuentaDestino", 0) + +lock = threading.Lock() +threads = [] + +for i in range(100): + threads.append(BankTransferThread(cuenta1, cuenta2, 1)) + +for thread in threads: + thread.start() + +for thread in threads: + thread.join() + +print(cuenta1) +print(cuenta2) \ No newline at end of file diff --git a/02.Threads/P2.19-Lock-consucutivos.py b/02.Threads/P2.19-Lock-consucutivos.py new file mode 100644 index 0000000..02e1172 --- /dev/null +++ b/02.Threads/P2.19-Lock-consucutivos.py @@ -0,0 +1,14 @@ +import threading + +algo = 0 + +lock = threading.Lock() + +lock.acquire() +algo +=1 + +lock.acquire() +algo += 2 +lock.release() + +print(algo) \ No newline at end of file diff --git a/02.Threads/P2.19a-RLock.py b/02.Threads/P2.19a-RLock.py new file mode 100644 index 0000000..dd1a219 --- /dev/null +++ b/02.Threads/P2.19a-RLock.py @@ -0,0 +1,15 @@ +import threading + +algo = 0 + +rlock = threading.RLock() + +rlock.acquire() +algo += 1 + +rlock.acquire() +algo += 2 +rlock.release() +rlock.release() + +print(algo) \ No newline at end of file diff --git a/02.Threads/P2.20-Condicionales.py b/02.Threads/P2.20-Condicionales.py new file mode 100644 index 0000000..c85c1a1 --- /dev/null +++ b/02.Threads/P2.20-Condicionales.py @@ -0,0 +1,25 @@ + +import threading + +def ping(cond): + for _ in range(20): + with cond: + cond.wait() + print ("ping") + cond.notify() + +def pong(cond): + for _ in range(20): + with cond: + cond.wait() + print ("pong") + cond.notify() + +cond = threading.Condition() + +t1= threading.Thread(target=ping, args=(cond,)) +t2=threading.Thread(target=pong, args=(cond,)) +t1.start() +t2.start() +with cond: + cond.notify() \ No newline at end of file diff --git a/02.Threads/P2.21-Semaforos.py b/02.Threads/P2.21-Semaforos.py new file mode 100644 index 0000000..5fa5738 --- /dev/null +++ b/02.Threads/P2.21-Semaforos.py @@ -0,0 +1,35 @@ +import threading +import time +import logging + +logging.basicConfig(level=logging.DEBUG, + format='(%(threadName)-9s) %(message)s',) + +class ThreadPool(object): + def __init__(self): + super(ThreadPool, self).__init__() + self.active = [] + self.lock = threading.Lock() + def makeActive(self, name): + with self.lock: + self.active.append(name) + logging.debug('Running: %s', self.active) + def makeInactive(self, name): + with self.lock: + self.active.remove(name) + logging.debug('Running: %s', self.active) + +def f(s, pool): + logging.debug('Esperando para unirse al grupo') + with s: + name = threading.current_thread().name + pool.makeActive(name) + time.sleep(0.5) + pool.makeInactive(name) + + +pool = ThreadPool() +s = threading.Semaphore(3) +for i in range(10): + t = threading.Thread(target=f, name='thread_'+str(i), args=(s, pool)) + t.start() \ No newline at end of file diff --git a/02.Threads/P2.22-Eventos.py b/02.Threads/P2.22-Eventos.py new file mode 100644 index 0000000..779e8f4 --- /dev/null +++ b/02.Threads/P2.22-Eventos.py @@ -0,0 +1,20 @@ +import threading +import time + +def genera_eventos(): + for x in range (5): + time.sleep(2) + ev.set() + +def escribe_algo(): + while (True): + ev.wait() + print ("hola") + ev.clear() + +ev = threading.Event() +T1 = threading.Thread(target=genera_eventos) +T2 = threading.Thread(target=escribe_algo) + +T1.start() +T2.start() \ No newline at end of file diff --git a/02.Threads/P2.23-Timer.py b/02.Threads/P2.23-Timer.py new file mode 100644 index 0000000..a1dbb27 --- /dev/null +++ b/02.Threads/P2.23-Timer.py @@ -0,0 +1,17 @@ +import threading +import time + +def tarea(num): + for _ in range (num): + print("Ejecutando tarea...") + time.sleep(1) + #print (threading.currentThread().name) + +veces = 10 +t = threading.Timer(3, tarea, [veces,]) +print("Iniciando hilo con temporizador") +t.start() #será ejecutado tras tres segundos +time.sleep(5) +#prueba para cancelar el hilo +print("Cancelando la tarea <>") +t.cancel() \ No newline at end of file diff --git a/02.Threads/P2.24-Barreras.py b/02.Threads/P2.24-Barreras.py new file mode 100644 index 0000000..0d90c59 --- /dev/null +++ b/02.Threads/P2.24-Barreras.py @@ -0,0 +1,14 @@ +import time +import random +import threading + +def f(): + time.sleep(random.randint(1,10)) + print("{} despertado: {}".format(threading.current_thread().name, time.ctime())) + barrera.wait() + print("{} pasó la barrera: {}\n".format(threading.current_thread().name, time.ctime())) + +barrera = threading.Barrier(5) +for _ in range(5): + t = threading.Thread(target=f) + t.start() \ No newline at end of file diff --git a/02.Threads/P2.25-Productor-consumidor.py b/02.Threads/P2.25-Productor-consumidor.py new file mode 100644 index 0000000..b390dad --- /dev/null +++ b/02.Threads/P2.25-Productor-consumidor.py @@ -0,0 +1,50 @@ +import threading +import time +import logging +import random +import queue + +logging.basicConfig(level=logging.DEBUG, + format='(%(threadName)-9s) %(message)s',) + +BUF_SIZE = 10 +q = queue.Queue(BUF_SIZE) + +class HiloProductor(threading.Thread): + def __init__(self,name=None): + super(HiloProductor,self).__init__() + self.name = name + + def run(self): + while True: + if not q.full(): + item = random.randint(1,10) + q.put(item) + logging.debug('Insertando "' + str(item) + + '" : ' + str(q.qsize()) + ' elementos en la cola') + time.sleep(random.random()) + return + +class HiloConsumidor(threading.Thread): + def __init__(self,name=None): + super(HiloConsumidor,self).__init__() + self.name = name + return + + def run(self): + while True: + if not q.empty(): + item = q.get() + logging.debug('Sacando "' + str(item) + + '" : ' + str(q.qsize()) + ' elementos en la cola') + time.sleep(random.random()) + return + +p = HiloProductor(name='productor') +p2 = HiloProductor(name='productor2') + +c = HiloConsumidor(name='consumidor') + +p.start() +p2.start() +c.start() \ No newline at end of file diff --git a/02.Threads/P2.26-Exception.py b/02.Threads/P2.26-Exception.py new file mode 100644 index 0000000..c67ebaf --- /dev/null +++ b/02.Threads/P2.26-Exception.py @@ -0,0 +1,13 @@ +import threading + +def f(): + pass + +try: + t = threading.Thread(target=f) + t.start() + t.start() +except Exception as e: + print("Error:", e) +print ("Final del programa") + \ No newline at end of file diff --git a/02.Threads/P2.27-Abort.py b/02.Threads/P2.27-Abort.py new file mode 100644 index 0000000..7265e68 --- /dev/null +++ b/02.Threads/P2.27-Abort.py @@ -0,0 +1,32 @@ +import threading +import time + +class HiloAbortable(threading.Thread): + + def __init__(self): + super(HiloAbortable, self).__init__() + self._abort_event = threading.Event() + + def abort(self): + self._abort_event.set() + + def aborted(self): + return self._abort_event.is_set() + + def run(self): + while (True): + if (self.aborted()): + print ("Hilo abortado") + break + #resto del trabajo a ejecutar + print ("trabajando...") + +h =HiloAbortable() +h.start() +time.sleep(1) +print ("Antes de invocación a abort()") +h.abort() +print ("Después de invocación de abort()") + + + diff --git a/03.Network-Sockets/P3.01-IPv4Address.py b/03.Network-Sockets/P3.01-IPv4Address.py new file mode 100644 index 0000000..05adbd9 --- /dev/null +++ b/03.Network-Sockets/P3.01-IPv4Address.py @@ -0,0 +1,17 @@ +import ipaddress + +ip = ipaddress.IPv4Address('224.0.0.1') + +print("Bits en la IP:", ip.max_prefixlen) +print("Multicast:", ip.is_multicast) +print("Privada:", ip.is_private) +print("Pública:", ip.is_global) +print("No es específica:", ip.is_unspecified) +print("Reservada:", ip.is_reserved) +print("Loopback:", ip.is_loopback) +print("Uso local:", ip.is_link_local) +ip1 = ip + 1 +print("IP siguiente:", ip1) +ip2 = ip - 1 +print("IP anterior:", ip2) +print(ip1 , "mayor que", ip2, ":", ip1 > ip2) diff --git a/03.Network-Sockets/P3.02-IPv4Network.py b/03.Network-Sockets/P3.02-IPv4Network.py new file mode 100644 index 0000000..7ca0d78 --- /dev/null +++ b/03.Network-Sockets/P3.02-IPv4Network.py @@ -0,0 +1,20 @@ +import ipaddress + +network = ipaddress.IPv4Network("192.168.1.0/24") + +print("Dirección de la red:", network.network_address) +print("Dirección de broadcast:", network.broadcast_address) +print("Máscara de red:", network.netmask) +print("Red y máscara de red:", network.with_netmask) +print("Red y máscara de host:", network.with_hostmask) +print("Longitud de la máscara de red", network.prefixlen) +print("Máximo número de equipos en la red:", network.num_addresses) +print("La red 192.168.0.0/16 la contiene:", + network.overlaps(ipaddress.IPv4Network("192.168.0.0/16"))) +print("Supernet:", network.supernet(prefixlen_diff=1)) +print("La red es una subnet de 192.168.0.0/16:", + network.subnet_of(ipaddress.IPv4Network("192.168.0.0/16"))) +print("La red es una supernet de 192.168.0.0/16:", + network.supernet_of(ipaddress.IPv4Network("192.168.0.0/16"))) +print("Comparar con 192.168.0.0/16:", + network.compare_networks(ipaddress.IPv4Network("192.168.0.0/16"))) diff --git a/03.Network-Sockets/P3.03-ObtenerIPpropia.py b/03.Network-Sockets/P3.03-ObtenerIPpropia.py new file mode 100644 index 0000000..42c309d --- /dev/null +++ b/03.Network-Sockets/P3.03-ObtenerIPpropia.py @@ -0,0 +1,6 @@ +import socket + +host = socket.gethostname() +ip = socket.gethostbyname(host) +print ("Nombre del equipo: %s" %host) +print ("Dirección IP: %s" %ip) \ No newline at end of file diff --git a/03.Network-Sockets/P3.04-ObtenerTodasIP.py b/03.Network-Sockets/P3.04-ObtenerTodasIP.py new file mode 100644 index 0000000..4165725 --- /dev/null +++ b/03.Network-Sockets/P3.04-ObtenerTodasIP.py @@ -0,0 +1,8 @@ +import ipaddress +import socket + +direcciones = socket.getaddrinfo(socket.gethostname(), None) +for ip in direcciones: + # ip_ver = ipaddress.ip_address(str(ip[4][0])) + # if ip_ver.version == 4: + print (ip[4][0]) diff --git a/03.Network-Sockets/P3.05-ObtenrIPExterna.py b/03.Network-Sockets/P3.05-ObtenrIPExterna.py new file mode 100644 index 0000000..22e9ef7 --- /dev/null +++ b/03.Network-Sockets/P3.05-ObtenrIPExterna.py @@ -0,0 +1,9 @@ +import socket + +try: + host = 'www.amazon.es' + #host = socket.getfqdn() + #host = 'DESKTOP-KEFADT0' + print ("IP de %s: %s" %(host,socket.gethostbyname(host))) +except socket.error as msg: + print ("%s: %s" %(host, msg)) \ No newline at end of file diff --git a/03.Network-Sockets/P3.06-Nslookup.py b/03.Network-Sockets/P3.06-Nslookup.py new file mode 100644 index 0000000..ed3351a --- /dev/null +++ b/03.Network-Sockets/P3.06-Nslookup.py @@ -0,0 +1,8 @@ +import socket + +ip = "216.58.209.69" +try: + dominio = socket.gethostbyaddr(ip)[0] + print ("La IP %s tiene una entrada DNS: %s" %(ip, dominio)) +except socket.error as msg: + print ("%s: %s" %(ip, msg)) \ No newline at end of file diff --git a/03.Network-Sockets/P3.07-tcpserver-try.py b/03.Network-Sockets/P3.07-tcpserver-try.py new file mode 100644 index 0000000..0e9bf04 --- /dev/null +++ b/03.Network-Sockets/P3.07-tcpserver-try.py @@ -0,0 +1,18 @@ +import socket + +HOST = '127.0.0.1' # direccion de loopback standard para localhost +PORT = 2000 # Puerto de escucha + +s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +try: + s.bind((HOST, PORT)) + s.listen(1) + conn, addr = s.accept() #función bloqueante + print (f"Conexión exitosa con el cliente. IP ({addr[0]}) Puerto ({addr[1]})") + #cerramos la conexión con ese cliente + conn.close() +except socket.error as exc: + print ("Excepción de socket: %s" % exc) +finally: + #cerramos la escucha general de nuestro servidor + s.close() \ No newline at end of file diff --git a/03.Network-Sockets/P3.08-tcpclient-try.py b/03.Network-Sockets/P3.08-tcpclient-try.py new file mode 100644 index 0000000..82a2897 --- /dev/null +++ b/03.Network-Sockets/P3.08-tcpclient-try.py @@ -0,0 +1,14 @@ +import socket + +HOST = '127.0.0.1' +PORT = 2000 + +s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +try: + s.connect((HOST, PORT)) + print('Conectado con éxito') +except socket.error as exc: + print ("Excepción de socket: %s" % exc) +finally: + #cerramos la conexión, aunque el servidor ya la habrá cerrado + s.close() \ No newline at end of file diff --git a/03.Network-Sockets/P3.09-tcpserver-datos-with.py b/03.Network-Sockets/P3.09-tcpserver-datos-with.py new file mode 100644 index 0000000..ab20a62 --- /dev/null +++ b/03.Network-Sockets/P3.09-tcpserver-datos-with.py @@ -0,0 +1,17 @@ +import socket + +HOST = '' # todas las interfaces locales a la escucha +PORT = 2000 # Puerto de escucha + +with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind((HOST, PORT)) + s.listen() + conn, addr = s.accept() #línea bloqueante + with conn: + print(f"Conexión exitosa con el cliente. IP ({addr[0]}) Puerto ({addr[1]})") + while True: + data = conn.recv(1024) #línea bloqueante + print (data) + if data==b"0": + break + conn.sendall(b"mensaje recibido") diff --git a/03.Network-Sockets/P3.09b-tcpserver-datos-with-try.py b/03.Network-Sockets/P3.09b-tcpserver-datos-with-try.py new file mode 100644 index 0000000..42f80bc --- /dev/null +++ b/03.Network-Sockets/P3.09b-tcpserver-datos-with-try.py @@ -0,0 +1,23 @@ +from audioop import add +import socket + +HOST = '' # todas las interfaces locales a la escuchat +PORT = 2000 # Puerto de escucha + +try: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind((HOST, PORT)) + s.listen() + conn, addr = s.accept() #línea bloqueante + with conn: + print(f"Conexión exitosa con el cliente. IP ({addr[0]}) Puerto ({addr[1]})") + while True: + data = conn.recv(1024) #línea bloqueante + print (data) + if data==b"0": + break + conn.sendall(b"mensaje recibido") + +except socket.error as e: + print ("Error en socket: %s" % e) + \ No newline at end of file diff --git a/03.Network-Sockets/P3.10-tcpclient-datos-with.py b/03.Network-Sockets/P3.10-tcpclient-datos-with.py new file mode 100644 index 0000000..27c9c74 --- /dev/null +++ b/03.Network-Sockets/P3.10-tcpclient-datos-with.py @@ -0,0 +1,14 @@ +import socket + +HOST = '127.0.0.1' +PORT = 2000 + +with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.connect((HOST, PORT)) + print('Conectado con éxito') + s.send(b'Yo, tu cliente, te saludo.') + #numBytes = s.send(b'Yo, tu cliente, te saludo.') + #print (numBytes) + data = s.recv(1024) #línea bloqueante + +print('Recibido:', repr(data)) \ No newline at end of file diff --git a/03.Network-Sockets/P3.11-udpserver.py b/03.Network-Sockets/P3.11-udpserver.py new file mode 100644 index 0000000..537cd42 --- /dev/null +++ b/03.Network-Sockets/P3.11-udpserver.py @@ -0,0 +1,18 @@ +import socket + +HOST = '' +PORT = 2000 + +with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: + + s_addr = (HOST, PORT) + s.bind(s_addr) + #recibir + datos, addr = s.recvfrom(1024) #línea bloqueante + print('recibidos {} bytes de {}'.format(len(datos), addr)) + print(datos) + + #enviar + if datos: + sent = s.sendto(b"Saludos desde el Servidor UDP", addr) + print('enviados {} bytes de vuelta a {}'.format(sent, addr)) diff --git a/03.Network-Sockets/P3.11b-udpserver-bucle.py b/03.Network-Sockets/P3.11b-udpserver-bucle.py new file mode 100644 index 0000000..7501f37 --- /dev/null +++ b/03.Network-Sockets/P3.11b-udpserver-bucle.py @@ -0,0 +1,19 @@ +import socket + +HOST = '' +PORT = 2000 + +with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: + + s_addr = (HOST, PORT) + s.bind(s_addr) + while True: + #recibir + datos, addr = s.recvfrom(1024) #línea bloqueante + print('recibidos {} bytes de {}'.format(len(datos), addr)) + print(datos) + + #enviar + if datos: + sent = s.sendto(b"Saludos desde el Servidor UDP", addr) + print('enviados {} bytes de vuelta a {}'.format(sent, addr)) diff --git a/03.Network-Sockets/P3.12-udpclient.py b/03.Network-Sockets/P3.12-udpclient.py new file mode 100644 index 0000000..b4f659a --- /dev/null +++ b/03.Network-Sockets/P3.12-udpclient.py @@ -0,0 +1,19 @@ +import socket + +HOST = '127.0.0.1' +PORT = 2000 + +with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: + s_addr = (HOST, PORT) + server_address = (s_addr) + message = b'Saludos desde el cliente' + + # enviar + print('Enviando {!r}'.format(message)) + sent = s.sendto(message, server_address) + + # recibir + print('Esperando por la respuesta') + data, server = s.recvfrom(1024) #línea bloqueante + print('recibidos {!r}'.format(data)) + diff --git a/04.Servicios/P4.01-TcpServer-Forever.py b/04.Servicios/P4.01-TcpServer-Forever.py new file mode 100644 index 0000000..ebeb68b --- /dev/null +++ b/04.Servicios/P4.01-TcpServer-Forever.py @@ -0,0 +1,32 @@ +import socketserver + +class TCPSocketHandler(socketserver.BaseRequestHandler): + #Clase para manejar las conexiones, se instancia una por cliente + + def handle(self): + #medodo a sobreescribir para nuestro propio manejo + #self.request se refiere al socket client conectado + print (f"Se han conectado desde: {self.client_address[0]} [{self.client_address[1]}]") + while True: + self.data = self.request.recv(128).strip() + print("Datos recibidos: ", self.data) + #remitimos los mismos datos en mayúscula + self.request.sendall(self.data.upper()) + if self.data == b"": + break + if self.data ==b"#": + raise KeyboardInterrupt + +if __name__ == "__main__": + HOST, PORT = "", 2000 + + # instanciamos el socket servidor con la clase asociada de callback + server = socketserver.TCPServer((HOST, PORT), TCPSocketHandler) + + # activamos el servidor (ponemos a la espera de clientes) + # podemos provocar una excepción con Ctrl-C + try: + server.serve_forever() + except KeyboardInterrupt: + print ("servidor finalizado") + \ No newline at end of file diff --git a/04.Servicios/P4.02-TcpServer-Handle.py b/04.Servicios/P4.02-TcpServer-Handle.py new file mode 100644 index 0000000..515d3a5 --- /dev/null +++ b/04.Servicios/P4.02-TcpServer-Handle.py @@ -0,0 +1,33 @@ +import socketserver + +class TCPSocketHandler(socketserver.BaseRequestHandler): + #Clase para manejar las conexiones, se instancia una por cliente + + def handle(self): + #medodo a sobreescribir para nuestro propio manejo + #self.request se refiere al socket client conectado + print (f"Se han conectado desde: {self.client_address[0]} [{self.client_address[1]}]") + + self.data = self.request.recv(128).strip() + print("Datos recibidos: ", self.data) + #remitimos los mismos datos en mayúscula + self.request.sendall(self.data.upper()) + # if self.data == b"0": + # break + # if self.data ==b"#": + # raise KeyboardInterrupt + +if __name__ == "__main__": + HOST, PORT = "", 2000 + + # instanciamos el socket servidor con la clase asociada de callback + server = socketserver.TCPServer((HOST, PORT), TCPSocketHandler) + + # activamos el servidor (ponemos a la espera de clientes) + # podemos provocar una excepción con Ctrl-C + try: + while True: + server.handle_request() + except KeyboardInterrupt: + print ("servidor finalizado") + \ No newline at end of file diff --git a/04.Servicios/P4.03-ClienteTCP.py b/04.Servicios/P4.03-ClienteTCP.py new file mode 100644 index 0000000..b816e8c --- /dev/null +++ b/04.Servicios/P4.03-ClienteTCP.py @@ -0,0 +1,16 @@ +import socket + +HOST, PORT = "localhost", 2000 +data = "hola desde cliente tcp" + + +with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + #conectar + sock.connect((HOST, PORT)) + #enviar + sock.sendall(bytes(data + "\n", "utf-8")) + #recibir + recibido = str(sock.recv(64), "utf-8") + +print("Enviado: {}".format(data)) +print("Recibido: {}".format(recibido)) \ No newline at end of file diff --git a/04.Servicios/P4.03-TcpServer-Forever-shutdown.py b/04.Servicios/P4.03-TcpServer-Forever-shutdown.py new file mode 100644 index 0000000..76843f3 --- /dev/null +++ b/04.Servicios/P4.03-TcpServer-Forever-shutdown.py @@ -0,0 +1,59 @@ +from asyncio.windows_events import NULL +import socketserver +import time +import threading + +class TCPSocketHandler(socketserver.BaseRequestHandler): + #Clase para manejar las conexiones, se instancia una por cliente + # def __init__(self, server_address, RequestHandlerClass, ): + + def set_shutdown_request(self): + self.shutdown_request = True + + + def handle(self): + #medodo a sobreescribir para nuestro propio manejo + #self.request se refiere al socket client conectado + print (f"Se han conectado desde: {self.client_address[0]} [{self.client_address[1]}]") + #print (self.server.request_queue_size) + self.shutdown_request = False + while not self.shutdown_request: + print (self.shutdown_request) + self.data = self.request.recv(128).strip() + print("Datos recibidos: ", self.data) + #remitimos los mismos datos en mayúscula + self.request.sendall(self.data.upper()) + if self.data == b"0": + break + if self.data ==b"#": + raise KeyboardInterrupt + +def Servir(servidor): + + + # instanciamos el socket servidor con la clase asociada de callback + servidor = socketserver.TCPServer((HOST, PORT), TCPSocketHandler) + # activamos el servidor (ponemos a la escucha) + # podomos porvocar una excepción con Ctrl-C + try: + servidor.serve_forever() + except KeyboardInterrupt: + print ("servidor finalizado") + +if __name__ == "__main__": + HOST, PORT = "", 2000 + # instanciamos el socket servidor con la clase asociada de callback + server = socketserver.TCPServer((HOST, PORT), TCPSocketHandler) + server_thread = threading.Thread(target=server.serve_forever) + # Exit the server thread when the main thread terminates + server_thread.daemon = True + server_thread.start() + + print ("uno") + time.sleep(10) + print ("dos") + server. + server.shutdown() + print ("tres") + + \ No newline at end of file diff --git a/04.Servicios/P4.04-UDPServer.py b/04.Servicios/P4.04-UDPServer.py new file mode 100644 index 0000000..ed0aad7 --- /dev/null +++ b/04.Servicios/P4.04-UDPServer.py @@ -0,0 +1,26 @@ +import socketserver + +class UDPHandler(socketserver.BaseRequestHandler): + #self.request es el par [datos,socketServidor] + + def handle(self): + data = self.request[0].strip() + sock = self.request[1] + print(" El cliente: {} envió:".format(self.client_address[0])) + print(data) + #bajo alguna circunstancia podemos detener el servidor con la siguiente línea + if data ==b"#": + raise KeyboardInterrupt + #envío de datos al cliente + sock.sendto(data.upper(), self.client_address) + +if __name__ == "__main__": + HOST, PORT = "", 2000 + with socketserver.UDPServer((HOST, PORT), UDPHandler) as server: + # activamos el servidor (ponemos a la escucha) + # podomos porvocar una excepción con Ctrl-C + try: + server.serve_forever() + except KeyboardInterrupt: + print ("servidor finalizado") + \ No newline at end of file diff --git a/04.Servicios/P4.05-ClienteUDP.py b/04.Servicios/P4.05-ClienteUDP.py new file mode 100644 index 0000000..21f958e --- /dev/null +++ b/04.Servicios/P4.05-ClienteUDP.py @@ -0,0 +1,15 @@ +import socket + +HOST, PORT = "localhost", 2000 +data = "hola desde cliente udp" + +#definir +with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: + #se puede observar que no hay conectar + #enviar + sock.sendto(bytes(data + "\n", "utf-8"), (HOST, PORT)) + #recibir + recibido = str(sock.recv(64), "utf-8") + +print("Enviado: {}".format(data)) +print("Recibido: {}".format(recibido)) \ No newline at end of file diff --git a/04.Servicios/P4.06-TcpServerStream.py b/04.Servicios/P4.06-TcpServerStream.py new file mode 100644 index 0000000..1d68e22 --- /dev/null +++ b/04.Servicios/P4.06-TcpServerStream.py @@ -0,0 +1,38 @@ +import socketserver + +class TCPStreamHandler(socketserver.StreamRequestHandler): + #Clase para manejar las conexiones, se instancia una por cliente + #transmisión de datos por stream + + def handle(self): + # self.rfile es un stream de lectura + # self.wfile es un stream de escritura + print (f"Se han conectado desde: {self.client_address[0]} [{self.client_address[1]}]") + while True: + self.data = self.rfile.readline().strip() + print("Datos recibidos: ", self.data) + #remitimos los mismos datos en mayúscula + self.wfile.write(self.data.upper()) + #self.wfile.writelines((b"uno", b"dos",b"tres")) + if self.data == b"": + break + if self.data ==b"#": + raise KeyboardInterrupt + + + +if __name__ == "__main__": + HOST, PORT = "", 2000 + + # instanciamos el socket servidor con la clase asociada de callback + server = socketserver.TCPServer((HOST, PORT), TCPStreamHandler) + + # activamos el servidor (ponemos a la escucha) + # podomos porvocar una excepción con Ctrl-C + try: + server.serve_forever() + except KeyboardInterrupt: + print ("servidor finalizado") + + + diff --git a/04.Servicios/P4.07-TcpServerThreding.py b/04.Servicios/P4.07-TcpServerThreding.py new file mode 100644 index 0000000..d077333 --- /dev/null +++ b/04.Servicios/P4.07-TcpServerThreding.py @@ -0,0 +1,29 @@ +import threading +import socketserver + +class ThreadedTCPRequestHandler(socketserver.StreamRequestHandler): + + def handle(self): + data = self.rfile.readline().strip().decode('ascii') + cur_thread = threading.currentThread() + print (threading.current_thread().name) + response = bytes("{}: {}".format(cur_thread.name, data), 'ascii') + self.request.sendall(response) + +class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): + pass + +if __name__ == "__main__": + HOST, PORT = "", 2000 + server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler) + + # activamos el servidor (ponemos a la escucha) + # podomos porvocar una excepción con Ctrl-C + try: + server_thread = threading.Thread(target=server.serve_forever) + server_thread.start() + while True: + pass + except KeyboardInterrupt: + print ("servidor finalizado") + \ No newline at end of file diff --git a/04.Servicios/P4.08-TcpServerAsyncio.py b/04.Servicios/P4.08-TcpServerAsyncio.py new file mode 100644 index 0000000..8d166b1 --- /dev/null +++ b/04.Servicios/P4.08-TcpServerAsyncio.py @@ -0,0 +1,27 @@ +import asyncio + +async def handle_echo(reader, writer): + data = await reader.readline() + mensaje = data.decode() + addr = writer.get_extra_info('peername') + + print(f"Recibido {mensaje!r} de {addr!r}") + + print(f"Enviado: {mensaje!r}") + writer.write(data) + await writer.drain() + + print("Cliente cerrado") + writer.close() + +async def main(): + server = await asyncio.start_server( + handle_echo, '127.0.0.1', 2000) + + addrs = ', '.join(str(sock.getsockname()) for sock in server.sockets) + print(f'Servidor en {addrs}') + + async with server: + await server.serve_forever() + +asyncio.run(main()) \ No newline at end of file diff --git a/04.Servicios/P4.09-AdivinaNumero.py b/04.Servicios/P4.09-AdivinaNumero.py new file mode 100644 index 0000000..a1e28a7 --- /dev/null +++ b/04.Servicios/P4.09-AdivinaNumero.py @@ -0,0 +1,28 @@ +import socket +import random + +IP = '' +PORT = 2000 +adivinar = random.randrange(1,9) + +with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind((IP,PORT)) + s.listen() + print("Servidor escuchando") + print("Número a adivinar: " +str(adivinar)) + + (cli,add) = s.accept() + print("Cliente conectado en:",add) + + cli.send(b"Intenta adivinar mi numero! ") + while True : + data = cli.recv(64).decode() + print (data) + if int(data) == adivinar: + cli.send(b"HAS ACERTADO") + break + elif int(data) > adivinar: + cli.send(b"Mi numero es menor ") + else: + cli.send(b"Mi numero es mayor") + cli.close() \ No newline at end of file diff --git a/04.Servicios/P4.10-AdivinaNumeroMulti.py b/04.Servicios/P4.10-AdivinaNumeroMulti.py new file mode 100644 index 0000000..aeae32c --- /dev/null +++ b/04.Servicios/P4.10-AdivinaNumeroMulti.py @@ -0,0 +1,36 @@ +import socket +import random +import threading + +adivinar = random.randrange(1,9) + +def ManejaCliente(c,a): + c.send(b"Intenta adivinar mi numero! ") + while True : + data = c.recv(64).decode() + print (data) + if int(data) == adivinar: + c.send(b"HAS ACERTADO") + break + elif int(data) > adivinar: + c.send(b"Mi numero es menor ") + else: + c.send(b"Mi numero es mayor") + c.close() + +if __name__ == '__main__': + IP = '' + PORT = 2000 + + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind((IP,PORT)) + s.listen() + print("Servidor escuchando") + print("Número a adivinar: " +str(adivinar)) + + while True: + (cli,addr) = s.accept() + print("Cliente conectado en:",addr) + #con cada conexión iniciamos un nuevo hilo que lo atienda + t = threading.Thread(target=ManejaCliente, args=(cli,addr)) + t.start() \ No newline at end of file diff --git a/04.Servicios/P4.11-PPTServidorBase.py b/04.Servicios/P4.11-PPTServidorBase.py new file mode 100644 index 0000000..bc4e465 --- /dev/null +++ b/04.Servicios/P4.11-PPTServidorBase.py @@ -0,0 +1,157 @@ +import socket +import threading +import time + +class Jugador: + def __init__(self): + self._nick = "" #nombre del jugador + self._addr = "" #dirección del cliente + self._jugada= "" #piedra/papel/tijera + self._puntos= 0 + + @property + def nick(self): + return self._nick + + @property + def addr(self): + return self._addr + + @property + def jugada(self): + return self._jugada + + @property + def puntos(self): + return self._puntos + + @property + def libre(self): + if self._nick == "": + return True + else: + return False + + @property + def sinJugar(self): + if self._jugada == "": + return True + else: + return False + + @nick.setter + def nick(self, nombre): + self._nick = nombre + + @addr.setter + def addr(self, nombre): + self._addr = nombre + + @jugada.setter + def jugada(self, nombre): + if nombre in ["piedra","papel","tijera",""]: + self._jugada = nombre + + @puntos.setter + def puntos(self, nombre): + self._puntos = nombre + + def puntuar(self): + print (self._puntos) + self._puntos += 1 + + def arbitrar(self,otroJugador): + #devuelve 0 si empate, -1 si gana otroJugador, 1 si gana el objeto actual + if ((self.jugada =="piedra" and otroJugador.jugada =="tijera") or + (self.jugada =="tijera" and otroJugador.jugada =="papel") or + (self.jugada =="papel" and otroJugador.jugada =="piedra")): + return 1 + elif ((otroJugador.jugada =="piedra" and self.jugada =="tijera") or + (otroJugador.jugada =="tijera" and self.jugada =="papel") or + (otroJugador.jugada =="papel" and self.jugada =="piedra")): + return -1 + else: + return 0 + +class ManejoCliente(threading.Thread): + def __init__(self,clientAddress,clientsocket): + threading.Thread.__init__(self) + self.csocket = clientsocket + self.cAddress = clientAddress + print ("Cliente conectado desde: ", self.cAddress) + + def run(self): + print ("Escuchando a peticiones de cliente: ", self.cAddress) + #mensaje de bienvenida con el protocolo + bienvenida ="#INSCRIBIR#nombre#\n#JUGADA#{piedra|papel|tijera}#\n#PUNTUACION#" + self.csocket.send(bytes(bienvenida,'UTF-8')) + + while True: + data = self.csocket.recv(512).decode("utf_8") + print ("Enviado desde cliente:<",data,">") + subdatos = data.split("#") + respuesta="#OK#" + if subdatos[1] == "INSCRIBIR": + if jugador1.libre: + jugador1.nick = subdatos[2] + jugador1.addr = self.cAddress + elif jugador2.libre: + jugador2.nick = subdatos[2] + jugador2.addr = self.cAddress + else: + respuesta="#NOK#ya hay dos jugadores#" + elif subdatos[1] == "JUGADA": + #comprobra valor válido + if subdatos[2] not in ["piedra","papel","tijera"]: + respuesta="#NOK#valores válidos: piedra/papel/tijera#" + #comprobar autenticidad IP+puerto registrados + elif self.cAddress in [jugador1.addr, jugador2.addr]: + #estamos con el jugador 1 + if self.cAddress == jugador1.addr: + jugador1.jugada = subdatos[2] + #pausar hasta que jugador 2 no haga su jugada + while (jugador2.sinJugar): + time.sleep(0.1) + #estamos con el jugador 2 + else: + jugador2.jugada = subdatos[2] + #pausar hasta que jugador 1 no haga su jugada + while (jugador1.sinJugar): + print (jugador1.sinJugar) + time.sleep(0.1) + #gana el 1 + if jugador1.arbitrar(jugador2)>0: + jugador1.puntuar() + respuesta="#OK#GANADOR:" + jugador1.nick + "#" + #gana el 2 + elif jugador1.arbitrar(jugador2)<0: + jugador2.puntuar() + respuesta="#OK#GANADOR:" + jugador2.nick + "#" + else: + respuesta ="#OK#EMPATE#" + #pequeña trampilla para que no colapsen los hilos + time.sleep(0.5) + jugador1.jugada ="" + jugador2.jugada ="" + #la ip+puerto del jugador no estaba en la partida + else: + respuesta="#NOK#el jugador no está en la partida#" + elif subdatos[1] == "PUNTUACION": + respuesta="#OK#" + jugador1.nick + ":" + str(jugador1.puntos) + "#" + jugador2.nick + ":" + str(jugador2.puntos) + "#" + + self.csocket.send(bytes(respuesta,'UTF-8')) + +if __name__ == '__main__': + jugador1 = Jugador() + jugador2 = Jugador() + HOST = "" + PORT = 2000 + server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + #server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + server.bind((HOST, PORT)) + print("Servidor iniciado. Esperando clientes...") + while True: + server.listen(1) + clientsock, clientAddress = server.accept() + t = ManejoCliente(clientAddress, clientsock) + t.start() \ No newline at end of file diff --git a/04.Servicios/P4.12-PPTClienteBasico.py b/04.Servicios/P4.12-PPTClienteBasico.py new file mode 100644 index 0000000..97092fd --- /dev/null +++ b/04.Servicios/P4.12-PPTClienteBasico.py @@ -0,0 +1,14 @@ +import socket + +SERVER = "127.0.0.1" +PORT = 2000 +client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +client.connect((SERVER, PORT)) +while True: + in_data = client.recv(1024) + print("From Server :" ,in_data.decode()) + out_data = input() + client.sendall(bytes(out_data,'UTF-8')) + if out_data=='fin': + break +client.close() \ No newline at end of file diff --git a/04.Servicios/P4.13-PPTClienteGUI.py b/04.Servicios/P4.13-PPTClienteGUI.py new file mode 100644 index 0000000..b9b0370 --- /dev/null +++ b/04.Servicios/P4.13-PPTClienteGUI.py @@ -0,0 +1,50 @@ +import socket +from tkinter import * + +def conectarServidor(): + global client + client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + client.connect((SERVER, PORT)) + lblInfo["text"]= client.recv(1024).decode() + +def inscribir (): + global client + client.sendall(bytes("#INSCRIBIR#"+entNombre.get() +"#",'UTF-8')) + lblInfo["text"]= client.recv(1024).decode() + +def enviarJugada(jugada): + global client + client.sendall(bytes("#JUGADA#"+jugada+"#",'UTF-8')) + lblInfo["text"]= client.recv(1024).decode() + +def consultaPuntos(): + global client + client.sendall(bytes("#PUNTUACION#",'UTF-8')) + lblInfo["text"]= client.recv(1024).decode() + +#if __name__ == '__main__': +SERVER = "127.0.0.1" +PORT = 2000 +client = None +informacion ="" +fPPT = Tk() +fPPT.title("Piedra-Papel-Tijera") +fPPT.geometry("300x300") +fPPT.resizable(True, True) +lblInfo = Label(fPPT, text=informacion) +lblInfo.place(x=0,y=230) +btnConn = Button(fPPT, text = 'Conectar', command = conectarServidor) +btnConn.place(x = 150,y = 50) +entNombre = Entry(fPPT) +entNombre.place(x = 20,y=100) +btnInscribir = Button(fPPT, text = 'Inscribir', command = inscribir) +btnInscribir.place(x = 150,y = 100) +btnPiedra = Button(fPPT, text = 'piedra', command = lambda: enviarJugada("piedra")) +btnPiedra.place(x = 50,y = 150) +btnPapel = Button(fPPT, text = 'papel', command = lambda: enviarJugada("papel")) +btnPapel.place(x = 100,y = 150) +btnTijera = Button(fPPT, text = 'tijera', command = lambda: enviarJugada("tijera")) +btnTijera.place(x = 150,y = 150) +btnPuntos = Button(fPPT, text = 'Puntuación', command =consultaPuntos) +btnPuntos.place(x = 150,y = 200) +fPPT.mainloop() \ No newline at end of file diff --git a/04.Servicios/P4.13a-PPTClienteGUI-asincrono.py b/04.Servicios/P4.13a-PPTClienteGUI-asincrono.py new file mode 100644 index 0000000..61452ed --- /dev/null +++ b/04.Servicios/P4.13a-PPTClienteGUI-asincrono.py @@ -0,0 +1,55 @@ +import socket +import threading +from tkinter import * + +def conectarServidor(): + global client + client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + client.connect((SERVER, PORT)) + lblInfo["text"]= client.recv(1024).decode() + +def inscribir (): + global client + client.sendall(bytes("#INSCRIBIR#"+entNombre.get() +"#",'UTF-8')) + lblInfo["text"]= client.recv(1024).decode() + +def hiloJugada(cli, jug): + cli.sendall(bytes("#JUGADA#"+jug+"#",'UTF-8')) + lblInfo["text"]= cli.recv(1024).decode() + +def enviarJugada(jugada): + global client + h = threading.Thread(target=hiloJugada, args=[client,jugada]) + h.start() + +def consultaPuntos(): + global client + client.sendall(bytes("#PUNTUACION#",'UTF-8')) + lblInfo["text"]= client.recv(1024).decode() + +#if __name__ == '__main__': +SERVER = "127.0.0.1" +PORT = 2000 +client = None +informacion ="" +fPPT = Tk() +fPPT.title("Piedra-Papel-Tijera") +fPPT.geometry("300x300") +fPPT.resizable(True, True) +lblInfo = Label(fPPT, text=informacion) +lblInfo.place(x=0,y=230) +btnConn = Button(fPPT, text = 'Conectar', command = conectarServidor) +btnConn.place(x = 150,y = 50) +entNombre = Entry(fPPT) +entNombre.place(x = 20,y=100) +btnInscribir = Button(fPPT, text = 'Inscribir', command = inscribir) +btnInscribir.place(x = 150,y = 100) +btnPiedra = Button(fPPT, text = 'piedra', command = lambda: enviarJugada("piedra")) +btnPiedra.place(x = 50,y = 150) +btnPapel = Button(fPPT, text = 'papel', command = lambda: enviarJugada("papel")) +btnPapel.place(x = 100,y = 150) +btnTijera = Button(fPPT, text = 'tijera', command = lambda: enviarJugada("tijera")) +btnTijera.place(x = 150,y = 150) +btnPuntos = Button(fPPT, text = 'Puntuación', command =consultaPuntos) +btnPuntos.place(x = 150,y = 200) +fPPT.mainloop() \ No newline at end of file diff --git a/04.Servicios/P4.14-PPTServidorSondeo.py b/04.Servicios/P4.14-PPTServidorSondeo.py new file mode 100644 index 0000000..04b1a27 --- /dev/null +++ b/04.Servicios/P4.14-PPTServidorSondeo.py @@ -0,0 +1,160 @@ +import socket +import threading + +class Jugador: + def __init__(self): + self._nick = "" #nombre del jugador + self._addr = "" #dirección del cliente + self._jugada= "" #piedra/papel/tijera + self._puntos= 0 + + @property + def nick(self): + return self._nick + + @property + def addr(self): + return self._addr + + @property + def jugada(self): + return self._jugada + + @property + def puntos(self): + return self._puntos + + @property + def libre(self): + if self._nick == "": + return True + else: + return False + + @property + def sinJugar(self): + if self._jugada == "": + return True + else: + return False + + @nick.setter + def nick(self, nombre): + self._nick = nombre + + @addr.setter + def addr(self, nombre): + self._addr = nombre + + @jugada.setter + def jugada(self, nombre): + if nombre in ["piedra","papel","tijera",""]: + self._jugada = nombre + + @puntos.setter + def puntos(self, nombre): + self._puntos = nombre + + def puntuar(self): + print (self._puntos) + self._puntos += 1 + + def arbitrar(self,otroJugador): + #devuelve 0 si empate, -1 si gana otroJugador, 1 si gana el objeto actual + if ((self.jugada =="piedra" and otroJugador.jugada =="tijera") or + (self.jugada =="tijera" and otroJugador.jugada =="papel") or + (self.jugada =="papel" and otroJugador.jugada =="piedra")): + return 1 + elif ((otroJugador.jugada =="piedra" and self.jugada =="tijera") or + (otroJugador.jugada =="tijera" and self.jugada =="papel") or + (otroJugador.jugada =="papel" and self.jugada =="piedra")): + return -1 + else: + return 0 + +class ManejoCliente(threading.Thread): + def __init__(self,clientAddress,clientsocket): + threading.Thread.__init__(self) + self.csocket = clientsocket + self.cAddress = clientAddress + print ("Cliente conectado desde: ", self.cAddress) + + def run(self): + global numJugadaActual + print ("Escuchando a peticiones de cliente: ", self.cAddress) + #mensaje de bienvenida con el protocolo + bienvenida ="#INSCRIBIR#nombre#\n#JUGADA#{piedra|papel|tijera}#\n#RESULTADOJUGADA#numeroJugada#\n#PUNTUACION#" + self.csocket.send(bytes(bienvenida,'UTF-8')) + + while True: + data = self.csocket.recv(512).decode("utf_8") + print ("Enviado desde cliente:<",data,">") + subdatos = data.split("#") + respuesta="#OK#" + if subdatos[1] == "INSCRIBIR": + if jugador1.libre: + jugador1.nick = subdatos[2] + jugador1.addr = self.cAddress + elif jugador2.libre: + jugador2.nick = subdatos[2] + jugador2.addr = self.cAddress + else: + respuesta="#NOK#ya hay dos jugadores#" + elif subdatos[1] == "JUGADA": + #comprobra valor válido + if subdatos[2] not in ["piedra","papel","tijera"]: + respuesta="#NOK#valores válidos: piedra/papel/tijera#" + #comprobar autenticidad IP+puerto registrados + elif self.cAddress in [jugador1.addr, jugador2.addr]: + #estamos con el jugador 1 + if self.cAddress == jugador1.addr: + jugador1.jugada = subdatos[2] + #estamos con el jugador 2 + else: + jugador2.jugada = subdatos[2] + respuesta="#OK#" +str(numJugadaActual+1) +"#" + #comprobamos si podemos arbitrar jugada + with lock: + if (not jugador1.sinJugar and not jugador2.sinJugar): + #gana el 1 + if jugador1.arbitrar(jugador2)>0: + jugador1.puntuar() + historicoJug[len(historicoJug):] =["#OK#GANADOR:" + jugador1.nick + "#"] + #gana el 2 + elif jugador1.arbitrar(jugador2)<0: + jugador2.puntuar() + historicoJug[len(historicoJug):] =["#OK#GANADOR:" + jugador2.nick + "#"] + else: + historicoJug[len(historicoJug):] =["#OK#EMPATE#"] + jugador1.jugada ="" + jugador2.jugada ="" + numJugadaActual +=1 + #la ip+puerto del jugador no estaba en la partida + else: + respuesta="#NOK#el jugador no está en la partida#" + elif subdatos[1] == "RESULTADOJUGADA": + if int(subdatos[2])>0 and int(subdatos[2]) <= numJugadaActual: + respuesta =historicoJug[int(subdatos[2])-1] + else: + respuesta = "#NOK#número de jugada no válido#" + elif subdatos[1] == "PUNTUACION": + respuesta="#OK#" + jugador1.nick + ":" + str(jugador1.puntos) + "#" + jugador2.nick + ":" + str(jugador2.puntos) + "#" + + self.csocket.send(bytes(respuesta,'UTF-8')) + +if __name__ == '__main__': + jugador1 = Jugador() + jugador2 = Jugador() + numJugadaActual = 0 #almacena el número actual de jugada + historicoJug = [] #mensajes de ganador para cada jugada + lock = threading.Lock() + HOST = "" + PORT = 2000 + server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server.bind((HOST, PORT)) + print("Servidor iniciado. Esperando clientes...") + while True: + server.listen(1) + clientsock, clientAddress = server.accept() + t = ManejoCliente(clientAddress, clientsock) + t.start() \ No newline at end of file diff --git a/04.Servicios/P4.15-PPTClienteSondeoGUI.py b/04.Servicios/P4.15-PPTClienteSondeoGUI.py new file mode 100644 index 0000000..7f466ca --- /dev/null +++ b/04.Servicios/P4.15-PPTClienteSondeoGUI.py @@ -0,0 +1,59 @@ +import socket +from tkinter import * + +def conectarServidor(): + global client + client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + client.connect((SERVER, PORT)) + lblInfo["text"]= client.recv(1024).decode() + +def inscribir (): + global client + client.sendall(bytes("#INSCRIBIR#"+entNombre.get() +"#",'UTF-8')) + lblInfo["text"]= client.recv(1024).decode() + +def enviarJugada(jugada): + global client + client.sendall(bytes("#JUGADA#"+jugada+"#",'UTF-8')) + lblInfo["text"]= client.recv(1024).decode() + +def consultaPuntos(): + global client + client.sendall(bytes("#PUNTUACION#",'UTF-8')) + lblInfo["text"]= client.recv(1024).decode() + +def resultadoJugada(numJ): + global client + client.sendall(bytes("#RESULTADOJUGADA#"+numJ+"#",'UTF-8')) + lblInfo["text"]= client.recv(1024).decode() + +#if __name__ == '__main__': +SERVER = "127.0.0.1" +PORT = 2000 +client = None +informacion ="" +fPPT = Tk() +fPPT.title("Piedra-Papel-Tijera") +fPPT.geometry("300x300") +fPPT.resizable(True, True) +lblInfo = Label(fPPT, text=informacion) +lblInfo.place(x=0,y=230) +btnConn = Button(fPPT, text = 'Conectar', command = conectarServidor) +btnConn.place(x = 150,y = 50) +entNombre = Entry(fPPT) +entNombre.place(x = 20,y=100) +btnInscribir = Button(fPPT, text = 'Inscribir', command = inscribir) +btnInscribir.place(x = 150,y = 100) +btnPiedra = Button(fPPT, text = 'piedra', command = lambda: enviarJugada("piedra")) +btnPiedra.place(x = 50,y = 150) +btnPapel = Button(fPPT, text = 'papel', command = lambda: enviarJugada("papel")) +btnPapel.place(x = 100,y = 150) +btnTijera = Button(fPPT, text = 'tijera', command = lambda: enviarJugada("tijera")) +btnTijera.place(x = 150,y = 150) +spnNumJugada = Spinbox(fPPT, from_=1, to=99,increment=1) +spnNumJugada.place(x = 30,y=200, width=50) +btnResultado = Button(fPPT, text = 'Resultado', command = lambda: resultadoJugada(spnNumJugada.get())) +btnResultado.place(x = 80,y = 200) +btnPuntos = Button(fPPT, text = 'Puntuación', command =consultaPuntos) +btnPuntos.place(x = 150,y = 200) +fPPT.mainloop() \ No newline at end of file diff --git a/04.Servicios/P4.16-PPTServidorFullDuplex.py b/04.Servicios/P4.16-PPTServidorFullDuplex.py new file mode 100644 index 0000000..2265fde --- /dev/null +++ b/04.Servicios/P4.16-PPTServidorFullDuplex.py @@ -0,0 +1,180 @@ +import socket +import threading + +class Jugador: + def __init__(self): + self._nick = "" #nombre del jugador + self._addr = "" #dirección del cliente + self._jugada= "" #piedra/papel/tijera + self._puntos= 0 + self._puertoCallback = 0 + + @property + def nick(self): + return self._nick + + @property + def addr(self): + return self._addr + + @property + def jugada(self): + return self._jugada + + @property + def puntos(self): + return self._puntos + + @property + def puertoCallback(self): + return self._puertoCallback + + @property + def libre(self): + if self._nick == "": + return True + else: + return False + + @property + def sinJugar(self): + if self._jugada == "": + return True + else: + return False + + @nick.setter + def nick(self, nombre): + self._nick = nombre + + @addr.setter + def addr(self, nombre): + self._addr = nombre + + @jugada.setter + def jugada(self, nombre): + if nombre in ["piedra","papel","tijera",""]: + self._jugada = nombre + + @puntos.setter + def puntos(self, nombre): + self._puntos = nombre + + @puertoCallback.setter + def puertoCallback(self, puerto): + self._puertoCallback= int(puerto) + + def puntuar(self): + print (self._puntos) + self._puntos += 1 + + def arbitrar(self,otroJugador): + #devuelve 0 si empate, -1 si gana otroJugador, 1 si gana el objeto actual + if ((self.jugada =="piedra" and otroJugador.jugada =="tijera") or + (self.jugada =="tijera" and otroJugador.jugada =="papel") or + (self.jugada =="papel" and otroJugador.jugada =="piedra")): + return 1 + elif ((otroJugador.jugada =="piedra" and self.jugada =="tijera") or + (otroJugador.jugada =="tijera" and self.jugada =="papel") or + (otroJugador.jugada =="papel" and self.jugada =="piedra")): + return -1 + else: + return 0 + +class ManejoCliente(threading.Thread): + def __init__(self,clientAddress,clientsocket): + threading.Thread.__init__(self) + self.csocket = clientsocket + self.cAddress = clientAddress + self.puertoEscuchaCli = 0 + print ("Cliente conectado desde: ", self.cAddress) + + def run(self): + global numJugadaActual + print ("Escuchando a peticiones de cliente: ", self.cAddress) + #mensaje de bienvenida con el protocolo + bienvenida ="#INSCRIBIR#nombre#puertoEscucha#\n#JUGADA#{piedra|papel|tijera}#\n#PUNTUACION#" + self.csocket.send(bytes(bienvenida,'UTF-8')) + + while True: + data = self.csocket.recv(512).decode("utf_8") + print ("Enviado desde cliente:<",data,">") + subdatos = data.split("#") + respuesta="#OK#" + if subdatos[1] == "INSCRIBIR": + if jugador1.libre: + jugador1.nick = subdatos[2] + jugador1.addr = self.cAddress + jugador1.puertoCallback = subdatos[3] + elif jugador2.libre: + jugador2.nick = subdatos[2] + jugador2.addr = self.cAddress + jugador2.puertoCallback = subdatos[3] + else: + respuesta="#NOK#ya hay dos jugadores#" + elif subdatos[1] == "JUGADA": + #comprobra valor válido + if subdatos[2] not in ["piedra","papel","tijera"]: + respuesta="#NOK#valores válidos: piedra/papel/tijera#" + #comprobar autenticidad IP+puerto registrados + elif self.cAddress in [jugador1.addr, jugador2.addr]: + #estamos con el jugador 1 + if self.cAddress == jugador1.addr: + jugador1.jugada = subdatos[2] + #estamos con el jugador 2 + else: + jugador2.jugada = subdatos[2] + respuesta="#OK#" + #comprobamos si podemos arbitrar jugada + with lock: + if (not jugador1.sinJugar and not jugador2.sinJugar): + #gana el 1 + if jugador1.arbitrar(jugador2)>0: + jugador1.puntuar() + resultado ="#OK#GANADOR:" + jugador1.nick + "#" + #gana el 2 + elif jugador1.arbitrar(jugador2)<0: + jugador2.puntuar() + resultado ="#OK#GANADOR:" + jugador2.nick + "#" + else: + resultado ="#OK#EMPATE#" + jugador1.jugada ="" + jugador2.jugada ="" + t1 = threading.Thread(target=self.comunicaResultadoClientes, args=(resultado,1)) + t2 = threading.Thread(target=self.comunicaResultadoClientes, args=(resultado,2)) + t1.start() + t2.start() + + #la ip+puerto del jugador no estaba en la partida + else: + respuesta="#NOK#el jugador no está en la partida#" + elif subdatos[1] == "PUNTUACION": + respuesta="#OK#" + jugador1.nick + ":" + str(jugador1.puntos) + "#" + jugador2.nick + ":" + str(jugador2.puntos) + "#" + + self.csocket.send(bytes(respuesta,'UTF-8')) + + def comunicaResultadoClientes(self, resultado, numJugador): + + if numJugador == 1: + puerto = jugador1.puertoCallback + elif numJugador ==2: + puerto = jugador2.puertoCallback + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as cli: + cli.connect((self.cAddress[0], puerto)) + cli.sendall(bytes(resultado,'UTF-8')) + print ("resultado enviado a"+self.cAddress[0]+ ":"+cli.recv(1024).decode()) + +if __name__ == '__main__': + jugador1 = Jugador() + jugador2 = Jugador() + lock = threading.Lock() + HOST = "" + PORT = 2000 + server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server.bind((HOST, PORT)) + print("Servidor iniciado. Esperando clientes...") + while True: + server.listen(1) + clientsock, clientAddress = server.accept() + t = ManejoCliente(clientAddress, clientsock) + t.start() \ No newline at end of file diff --git a/04.Servicios/P4.17-PPTClienteFullDuplexGUI.py b/04.Servicios/P4.17-PPTClienteFullDuplexGUI.py new file mode 100644 index 0000000..95c602c --- /dev/null +++ b/04.Servicios/P4.17-PPTClienteFullDuplexGUI.py @@ -0,0 +1,80 @@ +import socket +import threading +from tkinter import * + +def conectarServidor(puertoCallback): + global client + client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + client.connect((SERVER, PORT)) + lblInfo["text"]= client.recv(1024).decode() + t = threading.Thread(target=escucharRespuestas, args=(puertoCallback,)) + t.daemon=True + t.start() + + +def inscribir (puerto): + global client + client.sendall(bytes("#INSCRIBIR#"+entNombre.get() +"#"+puerto+"#",'UTF-8')) + lblInfo["text"]= client.recv(1024).decode() + +def enviarJugada(jugada): + global client + client.sendall(bytes("#JUGADA#"+jugada+"#",'UTF-8')) + lblInfo["text"]= client.recv(1024).decode() + +def consultaPuntos(): + global client + client.sendall(bytes("#PUNTUACION#",'UTF-8')) + lblInfo["text"]= client.recv(1024).decode() + +def escucharRespuestas(puertoCallBack): + global informacion + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind((SERVER, puertoCallBack)) + print("Escucha en callback") + s.listen() + while True: + (cli,add) = s.accept() + with cli: + data = cli.recv(512).decode("utf_8") + print ("Enviado desde cliente:<",data,">") + informacion = data + #lblInfo["text"]=informacion esta línea no funcionaría ya que no se puede modificar el label desde este hilo + fPPT.event_generate("<>",when="tail") + cli.send(bytes("#OK#",'UTF-8')) + +def escribirResolucion(*args): + lblInfo["text"]=informacion + + +#if __name__ == '__main__': +SERVER = "127.0.0.1" +PORT = 2000 +client = None +informacion ="" +fPPT = Tk() +fPPT.title("Piedra-Papel-Tijera") +fPPT.geometry("300x300") +fPPT.resizable(True, True) +lblInfo = Label(fPPT, text=informacion ) +lblInfo.place(x=0,y=230) +lblPuerto = Label(fPPT, text="Puerto de escucha:") +lblPuerto.place(x=0,y=50) +entPuerto = Entry(fPPT,) +entPuerto.place(x = 110,y=50, width=30) +btnConn = Button(fPPT, text = 'Conectar', command = lambda: conectarServidor(int(entPuerto.get()))) +btnConn.place(x = 150,y = 50) +entNombre = Entry(fPPT) +entNombre.place(x = 20,y=100) +btnInscribir = Button(fPPT, text = 'Inscribir', command = lambda: inscribir(entPuerto.get())) +btnInscribir.place(x = 150,y = 100) +btnPiedra = Button(fPPT, text = 'piedra', command = lambda: enviarJugada("piedra")) +btnPiedra.place(x = 50,y = 150) +btnPapel = Button(fPPT, text = 'papel', command = lambda: enviarJugada("papel")) +btnPapel.place(x = 100,y = 150) +btnTijera = Button(fPPT, text = 'tijera', command = lambda: enviarJugada("tijera")) +btnTijera.place(x = 150,y = 150) +btnPuntos = Button(fPPT, text = 'Puntuación', command =consultaPuntos) +btnPuntos.place(x = 150,y = 200) +fPPT.bind("<>",escribirResolucion) +fPPT.mainloop() \ No newline at end of file diff --git a/04.Servicios/P4.18-Ftp-list.py b/04.Servicios/P4.18-Ftp-list.py new file mode 100644 index 0000000..6651c4f --- /dev/null +++ b/04.Servicios/P4.18-Ftp-list.py @@ -0,0 +1,25 @@ +import ftplib +#creadenciales FTP, la contraseña la cambian cada cierto tiempo +FTP_HOST = "ftp.dlptest.com" +FTP_USER = "dlpuser" +FTP_PASS = "rNrKYTX9g7z3RgJRmxWuGHbeu" + +def listCallback(line): + print(line) + +# conexión al servidor de FTP +ftp = ftplib.FTP(FTP_HOST, FTP_USER, FTP_PASS) +#forzar codificación UNICODE +ftp.encoding = "utf-8" +welcomeMessage = ftp.getwelcome() +print(welcomeMessage) + +#se puede obtener la respuesta a través de una función de callback +respMessage = ftp.retrlines("LIST", listCallback) +#también se puede obtener el resultado de forma directa +#respMessage = ftp.retrlines("LIST") +print ("-----------------------------") +print(respMessage) + +#cerrar la conexión +ftp.quit() \ No newline at end of file diff --git a/04.Servicios/P4.19-Ftp-Upload.py b/04.Servicios/P4.19-Ftp-Upload.py new file mode 100644 index 0000000..b2d3819 --- /dev/null +++ b/04.Servicios/P4.19-Ftp-Upload.py @@ -0,0 +1,29 @@ +import ftplib +#creadenciales FTP, la contraseña la cambian cada cierto tiempo +FTP_HOST = "ftp.dlptest.com" +FTP_USER = "dlpuser" +FTP_PASS = "rNrKYTX9g7z3RgJRmxWuGHbeu" + +def listCallback(line): + print(line) + +try: + # conexión al servidor de FTP + ftp = ftplib.FTP(FTP_HOST, FTP_USER, FTP_PASS) + #forzar codificación UNICODE + ftp.encoding = "utf-8" + welcomeMessage = ftp.getwelcome() + print(welcomeMessage) + + #fichero a subir + filename = "subido.txt" + with open(filename, "rb") as file: + # Usamos comando STOR para subirlo + ftp.storbinary(f"STOR {filename}", file) + # listamos el contenido para comprobar + ftp.dir(listCallback) + + #cerrar la conexión + ftp.quit() +except ftplib.all_errors as e: + errorcode_string = str(e).split(None, 1)[0] \ No newline at end of file diff --git a/04.Servicios/P4.20-Ftp-Download.py b/04.Servicios/P4.20-Ftp-Download.py new file mode 100644 index 0000000..64f8494 --- /dev/null +++ b/04.Servicios/P4.20-Ftp-Download.py @@ -0,0 +1,25 @@ +import ftplib +#creadenciales FTP, la contraseña la cambian cada cierto tiempo +FTP_HOST = "ftp.dlptest.com" +FTP_USER = "dlpuser" +FTP_PASS = "rNrKYTX9g7z3RgJRmxWuGHbeu" + +try: + # conexión al servidor de FTP + ftp = ftplib.FTP(FTP_HOST, FTP_USER, FTP_PASS) + #forzar codificación UNICODE + ftp.encoding = "utf-8" + welcomeMessage = ftp.getwelcome() + print(welcomeMessage) + + #bajamos el fichero subido anteriormente y lo renombramos a bajado.txt + fichero_enServidor = "subido.txt" + fichero_local = "bajado.txt" + with open(fichero_local, "wb") as file: + # usamos el comando RETR para descargar + ftp.retrbinary(f"RETR {fichero_enServidor}", file.write) + + #cerrar la conexión + ftp.quit() +except ftplib.all_errors as e: + errorcode_string = str(e).split(None, 1)[0] \ No newline at end of file diff --git a/04.Servicios/P4.21-email-smtp.py b/04.Servicios/P4.21-email-smtp.py new file mode 100644 index 0000000..a22527c --- /dev/null +++ b/04.Servicios/P4.21-email-smtp.py @@ -0,0 +1,32 @@ +import smtplib +from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText + +body = '''Hola desde el manual de threads&sockets +Este es un correo simple para probar que podemos enviar emails a graves mediante python +Saludos +''' +#direccion, contraseña y destinatario +enviado_por = 'jlcarnerosobrino@gmail.com' +password = 'poner aqui la contraseña' +to = 'jlcarnerosobrino@gmail.com' + +#Establecimiento MIME +mensaje = MIMEMultipart() +mensaje['From'] = enviado_por +mensaje['To'] = to +mensaje['Subject'] = 'Prueba' + +#Cuerpo y adjuntos para el correo +mensaje.attach(MIMEText(body, 'plain')) +#Sesión SMTP para el envío del correo +try: + session = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with port + session.starttls() #enable security + session.login(enviado_por, password) #login with mail_id and password + text = mensaje.as_string() + session.sendmail(enviado_por, to, text) + session.quit() + print('Mensaje enviado') +except: + print ('Algo fue incorrecto...') \ No newline at end of file diff --git a/04.Servicios/P4.22-email-imap.py b/04.Servicios/P4.22-email-imap.py new file mode 100644 index 0000000..c59e188 --- /dev/null +++ b/04.Servicios/P4.22-email-imap.py @@ -0,0 +1,36 @@ +import imaplib + +user = 'jlcarnerosobrino@gmail.com' +password = 'poner aqui la contraseña' +imap_url = 'imap.gmail.com' + + +def search(key, value, con): + result, data = con.search(None, key, '"{}"'.format(value)) + return data + +def get_emails(result_bytes): + msgs = [] + for num in result_bytes[0].split(): + typ, data = con.fetch(num, '(RFC822)') + msgs.append(data) + return msgs + +con = imaplib.IMAP4_SSL(imap_url) +con.login(user, password) +con.select('Inbox') +msgs = get_emails(search('FROM', 'jlcarnerosobrino@gmail.com', con)) + +for msg in msgs[::-1]: + for sent in msg: + if type(sent) is tuple: + content = str(sent[1], 'utf-8') + data = str(content) + try: + indexstart = data.find("ltr") + data2 = data[indexstart + 5: len(data)] + indexend = data2.find("") + print(data2[0: indexend]) + + except UnicodeEncodeError as e: + pass \ No newline at end of file diff --git a/04.Servicios/P4.23-Webbrowser.py b/04.Servicios/P4.23-Webbrowser.py new file mode 100644 index 0000000..b50d2ee --- /dev/null +++ b/04.Servicios/P4.23-Webbrowser.py @@ -0,0 +1,15 @@ +import webbrowser + +url1 = 'https://www.marcombo.com/' +url2 = 'https://www.amazon.es/' +url3 = 'https://www.google.com/' + +# Abrir la URL en una nueva pestaña si ya existe una ventana del navegador abierta +webbrowser.open_new_tab(url1) + +# Abrir la URL en una nueva ventana, si es posible +webbrowser.open_new(url2) + +edge_path = "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" +webbrowser.register('edge', None, webbrowser.BackgroundBrowser(edge_path)) +webbrowser.get('edge').open_new(url3) diff --git a/04.Servicios/P4.24-leerUrl.py b/04.Servicios/P4.24-leerUrl.py new file mode 100644 index 0000000..f78741d --- /dev/null +++ b/04.Servicios/P4.24-leerUrl.py @@ -0,0 +1,19 @@ +from urllib import request + +response = request.urlopen('http://www.python.org') + +print('RESPONSE:', response) +print('CODIGO HTTP: ', response.getcode()) +print('URL :', response.geturl()) + +headers = response.info() +print('DATE :', headers['date']) +print('HEADERS :') +print('---------') +print(headers) + +print('BODY :') +print('---------') +for _ in range (20): + linea = response.readline().decode('utf-8') + print(linea) \ No newline at end of file diff --git a/04.Servicios/P4.25-ApiREST-OpenWeather.py b/04.Servicios/P4.25-ApiREST-OpenWeather.py new file mode 100644 index 0000000..810e937 --- /dev/null +++ b/04.Servicios/P4.25-ApiREST-OpenWeather.py @@ -0,0 +1,19 @@ +from urllib import request +import json +ciudad="Ourense" +api_key = "obtener una api-key!!!!!" +unidades ="metric" +url = "https://api.openweathermap.org/data/2.5/weather?q=%s&units=%s&appid=%s" % (ciudad, unidades, api_key) +#print (url) +response = request.urlopen(url) +http_body = response.readline().decode('utf-8') +print (http_body) +#codificar la respuesta a json +data = json.loads(http_body) +#print(data) +#acceso al bloque main +main = data["main"] +#acceso a temperatura +temperatura = main["temp"] +#data = response.json()["main"]["temp"] +print ("La temperatura de " + ciudad + "es:" + str(temperatura)) \ No newline at end of file diff --git a/04.Servicios/P4.26-ConsumirAPIExterna.py b/04.Servicios/P4.26-ConsumirAPIExterna.py new file mode 100644 index 0000000..04d92c7 --- /dev/null +++ b/04.Servicios/P4.26-ConsumirAPIExterna.py @@ -0,0 +1,16 @@ +from urllib import parse +from urllib import request +import json + +#diccionario de datos a enviar +datos_consulta = {'cod-persona':245} +#codificación de los datos +encoded_args = parse.urlencode(datos_consulta).encode('utf-8') +#endpoint de nuestra petición +url = 'https://psp-api.free.beeceptor.com/persona' +#composición de la petición con la url y los datos POST a insertar en el header +response = request.urlopen(url, encoded_args).read().decode('utf-8') +#print(response) +datos = json.loads(response) +print ("Nombre: ", datos["nombre"]) +print ("Edad: ", datos["edad"]) diff --git a/04.Servicios/bajado.txt b/04.Servicios/bajado.txt new file mode 100644 index 0000000..d7d0960 --- /dev/null +++ b/04.Servicios/bajado.txt @@ -0,0 +1 @@ +hola, estoy haciendo pruebas con FTP \ No newline at end of file diff --git a/04.Servicios/subido.txt b/04.Servicios/subido.txt new file mode 100644 index 0000000..d7d0960 --- /dev/null +++ b/04.Servicios/subido.txt @@ -0,0 +1 @@ +hola, estoy haciendo pruebas con FTP \ No newline at end of file diff --git a/05.Seguridad/Datos_Encriptados.bin b/05.Seguridad/Datos_Encriptados.bin new file mode 100644 index 0000000..21c1f8b Binary files /dev/null and b/05.Seguridad/Datos_Encriptados.bin differ diff --git a/05.Seguridad/P5.01-Hash-MD5.py b/05.Seguridad/P5.01-Hash-MD5.py new file mode 100644 index 0000000..0b67d0f --- /dev/null +++ b/05.Seguridad/P5.01-Hash-MD5.py @@ -0,0 +1,13 @@ +import hashlib + +#hash co md5 de un texto +Texto = "Texto de prueba".encode("utf-8") +HashCode= hashlib.md5(Texto).hexdigest() +print("El hash de %s es: %s" % (Texto , HashCode)) + +#hash con md5 de un fichero +filename = input("Nombre de fichero: ") +with open(filename,"rb") as f: + bytes = f.read() + HashCode = hashlib.md5(bytes).hexdigest(); + print("El hash del fichero: %s es:\n%s" % (filename ,HashCode)) \ No newline at end of file diff --git a/05.Seguridad/P5.02-CifradoCesar.py b/05.Seguridad/P5.02-CifradoCesar.py new file mode 100644 index 0000000..1e0576f --- /dev/null +++ b/05.Seguridad/P5.02-CifradoCesar.py @@ -0,0 +1,28 @@ +alfabeto = 'ABCDEFGHIJKLMNÑOPQRSTUVWXYZ0123456789' +alfabetoCifrado = 'KLMNÑOPQRSTUVWXYZ0123456789ABCDEFGHIJ' + +def cifrarCesar(men): + mensajeCifrado= "" + men = men.upper() + for caracter in men: + if caracter in alfabeto: + index = alfabeto.index(caracter) + mensajeCifrado += alfabetoCifrado[index] + else: #si el carácter no existeen el alfabeto + mensajeCifrado += caracter + return mensajeCifrado + +def descifrarCesar (menCif): + mensajeDescifrado= "" + for caracter in menCif: + if caracter in alfabeto: + index = alfabetoCifrado.index(caracter) + mensajeDescifrado += alfabeto[index] + else: #si el carácter no existeen el alfabeto + mensajeDescifrado += caracter + return (mensajeDescifrado) + +print (cifrarCesar('En un lugar de la Mancha, vivía!')) +print (descifrarCesar('ÑW 4W U4PK1 NÑ UK VKWMQK, 5R5ÍK!')) + +assert (cifrarCesar("I love you!")=="R UY5Ñ 8Y4!") \ No newline at end of file diff --git a/05.Seguridad/P5.03-DES-key-iv.py b/05.Seguridad/P5.03-DES-key-iv.py new file mode 100644 index 0000000..8c6441c --- /dev/null +++ b/05.Seguridad/P5.03-DES-key-iv.py @@ -0,0 +1,28 @@ +from Crypto.Cipher import DES +import base64 +import os + +mensajeOriginal = "Visita GALICIA: el paraíso".encode("utf-8") +print ("Mensaja original:", mensajeOriginal.decode("utf-8")) + +key = b"abc123.." #establecemos una clave +iv = os.urandom(8) #generamos aleatoriamente un iv + +print (iv) + +#instanciamos un nuevo objeto DES +cipher = DES.new(key, DES.MODE_OFB,iv=iv) +#ciframos los datos +bytesCifrados = cipher.encrypt(mensajeOriginal) +print ("Bytes cifrados: ", bytesCifrados) +#para imprimir una mejor representación +mensajeCifrado = base64.b64encode(bytesCifrados).decode("utf-8") +print ("Mensaje Cifrado:", mensajeCifrado) + +#es necesario un nuevo objeto para descifrar +cipher = DES.new(key, DES.MODE_OFB,iv = iv) +#desciframos usando la misma key e iv +mensajeDescifrado = cipher.decrypt(bytesCifrados) +print ("Mensaje: ", mensajeDescifrado.decode()) + +assert (mensajeOriginal == mensajeDescifrado) \ No newline at end of file diff --git a/05.Seguridad/P5.04-3DES.py b/05.Seguridad/P5.04-3DES.py new file mode 100644 index 0000000..1912aed --- /dev/null +++ b/05.Seguridad/P5.04-3DES.py @@ -0,0 +1,32 @@ +from Crypto.Cipher import DES3 +from Crypto.Random import get_random_bytes +import base64 +import os + +mensajeOriginal = "Visita GALICIA: el paraíso".encode("utf-8") +print ("Mensaja original:", mensajeOriginal.decode("utf-8")) + +while True: + try: + key = DES3.adjust_key_parity(get_random_bytes(24)) + break + except ValueError: + pass +iv = os.urandom(8) #generamos aleatoriamente un iv + +#instanciamos un nuevo objeto DES +cipher = DES3.new(key, DES3.MODE_CFB,iv=iv) +#ciframos los datos +bytesCifrados = cipher.encrypt(mensajeOriginal) +print ("Bytes cifrados: ", bytesCifrados) +#para imprimir una mejor representación +mensajeCifrado = base64.b64encode(bytesCifrados).decode("utf-8") +print ("Mensaje Cifrado:", mensajeCifrado) + +#es necesario un nuevo objeto para descifrar +cipher = DES3.new(key, DES3.MODE_CFB,iv = iv) +#desciframos usando la misma key e iv +mensajeDescifrado = cipher.decrypt(bytesCifrados) +print ("Mensaje: ", mensajeDescifrado.decode()) + +assert (mensajeOriginal == mensajeDescifrado) \ No newline at end of file diff --git a/05.Seguridad/P5.05-DES3-file.py b/05.Seguridad/P5.05-DES3-file.py new file mode 100644 index 0000000..cc533de --- /dev/null +++ b/05.Seguridad/P5.05-DES3-file.py @@ -0,0 +1,29 @@ +from Crypto.Cipher import DES3 +from hashlib import md5 + +def encriptar (fileOrigen, fileDestino, key): + cipher = DES3.new(key, DES3.MODE_EAX, nonce=b'0') + with open(fileOrigen, 'rb') as input_file: + file_bytes = input_file.read() + enc_file_bytes = cipher.encrypt(file_bytes) + + with open(fileDestino, 'wb') as output_file: + output_file.write(enc_file_bytes) + +def desencriptar (fileOrigen, fileDestino, key): + cipher = DES3.new(key, DES3.MODE_EAX, nonce=b'0') + with open(fileOrigen, 'rb') as input_file: + file_bytes = input_file.read() + dec_file_bytes = cipher.decrypt(file_bytes) + + with open(fileDestino, 'wb') as output_file: + output_file.write(dec_file_bytes) + + +key = "abc123." + +key_hash = md5(key.encode('ascii')).digest() # 16-byte key +tdes_key = DES3.adjust_key_parity(key_hash) + +encriptar("textoPlano.txt","textoEncriptado.txt",tdes_key) +desencriptar("textoEncriptado.txt", "textoDesencriptado.txt",tdes_key) \ No newline at end of file diff --git a/05.Seguridad/P5.06-AES.py b/05.Seguridad/P5.06-AES.py new file mode 100644 index 0000000..73b7d79 --- /dev/null +++ b/05.Seguridad/P5.06-AES.py @@ -0,0 +1,21 @@ +from Crypto.Cipher import AES + +mensajeOriginal = b"Hola, algoritmo AES" +key = b'Clave de 16 Byte' +print ("Original: ", mensajeOriginal) + +#cifrar +cipher = AES.new(key, AES.MODE_EAX) #sin iv +mensajeCifrado, tag = cipher.encrypt_and_digest(mensajeOriginal) +print ("Cifrado: ", mensajeCifrado) + +#descifrar +cipher = AES.new(key, AES.MODE_EAX, nonce=cipher.nonce) +mensajeDescifrado = cipher.decrypt(mensajeCifrado) +try: + cipher.verify(tag) + print("Descifrado: ", mensajeDescifrado) +except ValueError: + print("Clave incorrecta o mensaje corrupto") + +assert (mensajeDescifrado == mensajeDescifrado) \ No newline at end of file diff --git a/05.Seguridad/P5.07-AES-iv.py b/05.Seguridad/P5.07-AES-iv.py new file mode 100644 index 0000000..44de652 --- /dev/null +++ b/05.Seguridad/P5.07-AES-iv.py @@ -0,0 +1,33 @@ +from Crypto.Cipher import AES +from Crypto.Random import get_random_bytes + +key = get_random_bytes(32) # Use a stored / generated key +MensajeOriginal = 'Pureba de encriptación con AES+key+iv' # This is your data +print ("Mensaje original: ", MensajeOriginal) + +#Convertir un string a un objeto de bytes codificado UNICODE +data = MensajeOriginal.encode('utf-8') + +# Encriptación +cipher_encrypt = AES.new(key, AES.MODE_CFB) +BytesEncriptados = cipher_encrypt.encrypt(data) + +# Nuestro datos y vector de inicialización +iv = cipher_encrypt.iv +MensajeEncriptado = BytesEncriptados +print ("Mensaje encriptado: ", MensajeEncriptado) +print ("Vector de inicialización: ", iv) + + +# Desencriptación +cipher_decrypt = AES.new(key, AES.MODE_CFB, iv=iv) +BytesDesncriptados = cipher_decrypt.decrypt(MensajeEncriptado) + +# Conversión de bytes a string +MensajeDesencriptado = BytesDesncriptados.decode('utf-8') +print ("Mensaje desencriptado: ", MensajeDesencriptado) + +#probamos coindidencia original-encriptado-desencriptado +assert MensajeOriginal == MensajeDesencriptado, 'El mensaje original no coincide con la encrptación-desencriptación' + +#https://nitratine.net/blog/post/python-encryption-and-decryption-with-pycryptodome/ \ No newline at end of file diff --git a/05.Seguridad/P5.08-Generar-clave-RSA.py b/05.Seguridad/P5.08-Generar-clave-RSA.py new file mode 100644 index 0000000..28a548a --- /dev/null +++ b/05.Seguridad/P5.08-Generar-clave-RSA.py @@ -0,0 +1,23 @@ +from Crypto.PublicKey import RSA + +codigoClave = "Unguessable" #conraseña +key = RSA.generate(2048) +#obtener clave privada +encrypted_key = key.export_key(passphrase=codigoClave, pkcs=8, + protection="scryptAndAES128-CBC") + +file_out = open("rsa_key_privada.bin", "wb") +file_out.write(encrypted_key) +file_out.close() + +print ("Clave privada:\n",encrypted_key) + +#obtener clave pública +print("Clave pública:\n",key.publickey().export_key()) + +#obtener la clave pública en base a la lectura del fichero de clave privada +encoded_key = open("rsa_key_privada.bin", "rb").read() +key = RSA.import_key(encoded_key, passphrase=codigoClave) + +print("Clave pública:\n",key.publickey().export_key()) +print(key) \ No newline at end of file diff --git a/05.Seguridad/P5.09-Generar-par-claves-RSA.py b/05.Seguridad/P5.09-Generar-par-claves-RSA.py new file mode 100644 index 0000000..a0582e9 --- /dev/null +++ b/05.Seguridad/P5.09-Generar-par-claves-RSA.py @@ -0,0 +1,12 @@ +from Crypto.PublicKey import RSA + +key = RSA.generate(2048) +private_key = key.export_key() +file_out = open("privada_usuario_A.pem", "wb") +file_out.write(private_key) +file_out.close() + +public_key = key.publickey().export_key() +file_out = open("publica_usuario_A.pem", "wb") +file_out.write(public_key) +file_out.close() \ No newline at end of file diff --git a/05.Seguridad/P5.10-RSA-encriptar.py b/05.Seguridad/P5.10-RSA-encriptar.py new file mode 100644 index 0000000..94354ac --- /dev/null +++ b/05.Seguridad/P5.10-RSA-encriptar.py @@ -0,0 +1,19 @@ +from Crypto.PublicKey import RSA +from Crypto.Random import get_random_bytes +from Crypto.Cipher import AES, PKCS1_OAEP + +data = "La criptografía a través en Python a través de <> es consistente".encode("utf-8") +file_out = open("Datos_Encriptados.bin", "wb") + +recipient_key = RSA.import_key(open("publica_usuario_A.pem").read()) +session_key = get_random_bytes(16) + +# Encriptar la sesión con la clave pública del usuario_A +cipher_rsa = PKCS1_OAEP.new(recipient_key) +enc_session_key = cipher_rsa.encrypt(session_key) + +# Encriptar los datos con la sesión de AES +cipher_aes = AES.new(session_key, AES.MODE_EAX) +ciphertext, tag = cipher_aes.encrypt_and_digest(data) +[ file_out.write(x) for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext) ] +file_out.close() \ No newline at end of file diff --git a/05.Seguridad/P5.11-RSA-desencriptar.py b/05.Seguridad/P5.11-RSA-desencriptar.py new file mode 100644 index 0000000..15b04bc --- /dev/null +++ b/05.Seguridad/P5.11-RSA-desencriptar.py @@ -0,0 +1,18 @@ +from Crypto.PublicKey import RSA +from Crypto.Cipher import AES, PKCS1_OAEP + +file_in = open("Datos_Encriptados.bin", "rb") + +private_key = RSA.import_key(open("privada_usuario_A.pem").read()) + +enc_session_key, nonce, tag, ciphertext = \ + [ file_in.read(x) for x in (private_key.size_in_bytes(), 16, 16, -1) ] + +# Desencriptar la desión RSA con la clave privada del usuario_A +cipher_rsa = PKCS1_OAEP.new(private_key) +session_key = cipher_rsa.decrypt(enc_session_key) + +# Desencptar los datos ocn la sesión AES +cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce) +data = cipher_aes.decrypt_and_verify(ciphertext, tag) +print(data.decode("utf-8")) \ No newline at end of file diff --git a/05.Seguridad/P5.12-GenerarPar-DSA.py b/05.Seguridad/P5.12-GenerarPar-DSA.py new file mode 100644 index 0000000..e0e3ad4 --- /dev/null +++ b/05.Seguridad/P5.12-GenerarPar-DSA.py @@ -0,0 +1,15 @@ +from Crypto.PublicKey import DSA + +# Creación de clave DSA +key = DSA.generate(2048) +f = open("public_key.pem", "wb") +#grabación clave pública +f.write(key.publickey().export_key()) +f.close() +print ("Clave pública:\n", key.public_key().export_key()) + +f = open("private_key.pem", "wb") +#grabación clave privada +f.write(key.export_key()) +f.close() +print ("Clave privada:\n", key.export_key()) \ No newline at end of file diff --git a/05.Seguridad/P5.13-DSA-firmar.py b/05.Seguridad/P5.13-DSA-firmar.py new file mode 100644 index 0000000..9e97966 --- /dev/null +++ b/05.Seguridad/P5.13-DSA-firmar.py @@ -0,0 +1,21 @@ +from Crypto.PublicKey import DSA +from Crypto.Signature import DSS +from Crypto.Hash import SHA256 +import json + +f = open("private_key_firma.pem", "r") +key =DSA.import_key(f.read()) + +# Firmar un mensaje con la clave privada +mensaje = b"Comprobamos quien firma este mensaje" +hash_obj = SHA256.new(mensaje) +firmador = DSS.new(key, 'fips-186-3') +firma = firmador.sign(hash_obj) + +#creamos un fichero JSON con el texto y la firma +#lo codificamos en dos caracteres hexadecimales cada byte +mensajeFirmado = json.dumps({'mensaje':mensaje.hex(), 'firma':firma.hex()}) +#print (mensajeFirmado) +f = open("mensajefirmado.txt", "w") +f.write(mensajeFirmado) +f.close() \ No newline at end of file diff --git a/05.Seguridad/P5.14-DSA-verificar.py b/05.Seguridad/P5.14-DSA-verificar.py new file mode 100644 index 0000000..ff581d7 --- /dev/null +++ b/05.Seguridad/P5.14-DSA-verificar.py @@ -0,0 +1,26 @@ +from Crypto.PublicKey import DSA +from Crypto.Signature import DSS +from Crypto.Hash import SHA256 +import json + +#abrimos un fichero JSON con el texto y la firma +#viene codificamos en dos caracteres hexadecimales cada byte +f = open("mensajefirmado.txt", "r") +mensajeFirmado =f.read() +print (mensajeFirmado) +mensajeRecibido = json.loads(mensajeFirmado) + +#creamos un verificador con la firma leida en el fichero JSON +#usamos la clave pública del remitente +f = open("public_key_firma.pem", "r") +hash_obj = SHA256.new(bytes.fromhex(mensajeRecibido["mensaje"])) +pub_key = DSA.import_key(f.read()) +verificador = DSS.new(pub_key, 'fips-186-3') + +# Verificar la autenticidad del mensaje recibido +# en realidad lo hacemos del hash de todo el mensaje +try: + verificador.verify(hash_obj, bytes.fromhex(mensajeRecibido["firma"])) + print ("El mensaje es AUTENTICO") +except ValueError: + print ("Este mensaje no ha sido firmado de forma válida") \ No newline at end of file diff --git a/05.Seguridad/P5.15-SocketServer-SSL.py b/05.Seguridad/P5.15-SocketServer-SSL.py new file mode 100644 index 0000000..4e31de5 --- /dev/null +++ b/05.Seguridad/P5.15-SocketServer-SSL.py @@ -0,0 +1,24 @@ +import socket +import ssl + +HOST ='localhost' +PORT = 4444 + +context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) +context.load_cert_chain('cert-ssl\certificado.pem', 'cert-ssl\clave-privada.key') + +with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock: + sock.bind((HOST, PORT)) + sock.listen(5) + print (f"Servidor correiendo en: {HOST},{PORT}") + #solapaar el socket sobre SSL + with context.wrap_socket(sock, server_side=True) as ssock: + while True: + conn, addr = ssock.accept() + print (f"Conexión desde: {addr}") + #enviar datos + data = "Bienvenido al servidor SSL ("+HOST+":"+str(PORT)+")" + conn.sendall (data.encode("utf-8")) + #recibir datos + data =conn.recv() + print (data) \ No newline at end of file diff --git a/05.Seguridad/P5.16-SocketCliente-SSL.py b/05.Seguridad/P5.16-SocketCliente-SSL.py new file mode 100644 index 0000000..952779e --- /dev/null +++ b/05.Seguridad/P5.16-SocketCliente-SSL.py @@ -0,0 +1,20 @@ +import socket +import ssl + +HOST = 'localhost' +PORT = 4444 + +context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) +context.load_verify_locations('cert-ssl\certificado.pem') + +with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock: + #solapaar el socket sobre SSL + with context.wrap_socket(sock, server_hostname=HOST) as ssock: + print(ssock.version()) + ssock.connect((HOST, PORT)) + print ("Conexión con éxito") + #recibir datos + data = ssock.recv(1024) + print(f"Recibido: {data!r}") + #enviar datos + ssock.sendall("hola, soy un cliente SSL".encode("utf-8")) \ No newline at end of file diff --git a/05.Seguridad/cert-ssl/certificado.pem b/05.Seguridad/cert-ssl/certificado.pem new file mode 100644 index 0000000..3a8ba88 --- /dev/null +++ b/05.Seguridad/cert-ssl/certificado.pem @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDCzCCAfOgAwIBAgIUe0slvpJCoeeUc7PtK+dCV1sWsyQwDQYJKoZIhvcNAQEF +BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MCAXDTIyMDMyMzA5MDE1OFoYDzIxMjIw +MjI3MDkwMTU4WjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQCzYif3Rjbi3W4Hg1d5NmDYgZZLBOE6RUkaM2q8sMRl +/FGORmfjTslHTT4CqCTjfKNAXjgxx2zpDrzCuSJiI1Nxv2QIET9jqY2JzAvLrvci +nSe6fdWEnhDabXQDWpD/jAS5KCOakFulN5IIgFNAq6mYXo5/pWZbFH0Tt2cZW9wX +EjaVak+Dzcm6DNJs3o5itcLY85QeaZ9lI48LUyTd9TP5KewmwANLvHl1ycc9mo9C +xOEZwTgD7OKp6ZCRnEshsX75UCwCAVapXc6UP1Yfv2TFxHDLjVnb8M23qIAlL8Jw +vP0i21Mk2xjvxEimffSqRiNCMb24ZpIDATs4W6Mtf44hAgMBAAGjUzBRMB0GA1Ud +DgQWBBSMp0nB9rQ+o+MzzTjAT2bR1XDQ4zAfBgNVHSMEGDAWgBSMp0nB9rQ+o+Mz +zTjAT2bR1XDQ4zAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQBN +3RmNFQE41gty/c3Fmpha/YZ23Cn9QuMlwHhArT4ccXXmu/2xs0DCF4cUTZiiaqw9 +lvHG19G9UWwq+U6I1LGlTpoEuSrHWr22u+WhybVCJySf6tuTyUQMvc+yerNwMQAI +2gIg8mxZftqFRslcglS/tkklWaKy4MY4uQZgaZNhOqwzv/FehlydAhP1IyI6icSq +gFQvOZjcqBOeRWUiUQAvpTkmmTSeH0doY/zrZSClOOgoNR27PCzyQVAmQY/UMoYY +QW0vjZ7mWvbW5+7N9NtFgBHhYDdX40J50yc2DBjBdLMXt9lKP+Uk2b84t1mpm3G6 +lcimjfvCyoyF/l6V5CkF +-----END CERTIFICATE----- diff --git a/05.Seguridad/cert-ssl/clave-privada.key b/05.Seguridad/cert-ssl/clave-privada.key new file mode 100644 index 0000000..498e17f --- /dev/null +++ b/05.Seguridad/cert-ssl/clave-privada.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCzYif3Rjbi3W4H +g1d5NmDYgZZLBOE6RUkaM2q8sMRl/FGORmfjTslHTT4CqCTjfKNAXjgxx2zpDrzC +uSJiI1Nxv2QIET9jqY2JzAvLrvcinSe6fdWEnhDabXQDWpD/jAS5KCOakFulN5II +gFNAq6mYXo5/pWZbFH0Tt2cZW9wXEjaVak+Dzcm6DNJs3o5itcLY85QeaZ9lI48L +UyTd9TP5KewmwANLvHl1ycc9mo9CxOEZwTgD7OKp6ZCRnEshsX75UCwCAVapXc6U +P1Yfv2TFxHDLjVnb8M23qIAlL8JwvP0i21Mk2xjvxEimffSqRiNCMb24ZpIDATs4 +W6Mtf44hAgMBAAECggEAALEQy7K/gIwkC1JLHogRaOF6kDK5D1LNSJojTuDjaUoA +0nX1uP/CY1VRKDx3IUfQJowQLpAXiK10/z1yx4pOwtqWStR0jE1eA269lAA7Q+QC +gsPHnys8MLbehbcaFZLy6/Ldd2qaRkqVsHm9zSSD1XND4tNjHa1Ra3BYoFWDWZbo +Ov9GXus12oDTHQr/gRqtjJfIxNOotPnsltVgcfmY+4DXRTsUU6UPIju1szFy/Mxf +AryPmENJKFgE2yl0FSdtsmOi5cCF421hVzditevQfP8u46K2h/rxy3rxuOZu5AVN +wOkOyR3PmfGVrjkQ3US+FnpNNAI+6qFAG5bTvyvN0wKBgQDow3TacfuouGCRqt64 +YnHDag/1TqvtI0Iwg7qFaKCJrFPjVvUDy8KAV+S8IPzIwWVFAuHGkVobC0gbqRAE +m3QNRYpQY2Wo+GniMPY+7/uTaU+NuhxwIzzj7hgqz1SjNVEtNajO10Gcfm2op9yN +f5DYv00Bot6pEPvLXlQfl3wLCwKBgQDFSoJg8I4yD+TWT30IKe9UgV9nuYvaRpq0 +nku23pjzrPgXqDd3x281KHtiQU2rMxfBdsi9iYSye2GtwVmkZKDgZsT7QdVcZc1z ++36FEpGnM7C+e6uuXr4X0cYZZ2CsIs0WZXzMkkgUl8kqTi9u34DWEAqce8s+7zXN +ywnJLA5nAwKBgQDOO5gGkKWMuUh+6GmL71Wi8g+PpxP3+ZyExcJ2v9w1/2UYcgyH +P3tnIfk9ovC2o3wp6ELJIDI48gcC0wmpO19Y/vts/JSvYOLYEc+stg8ubkmZZoQZ +627g+S2aiLcSIIR7TSbzlY/Bq9dXbtug150sHluJjphALhca+soIb7ztPwKBgBny +SaFMIbdNxc+1loD7WuFnPk/a5BypynDUnKqJLd5mMh6SXfEfxm1cTJXIdtl8F7S2 +1YGv00bR2S/LzOlE3q+EdIWCy/eh39pQCfygS42My8LRauu8xA1H5mCy6tDYptY6 +NKaG2nny2F7691wCguQkKfEYistVFGNjP384jxBXAoGAfbVG0D/GOL8j0NCIkU0g +I2I1VVVd3qwoSx0KudB67VXXuoeJ2EPJqrBLIm9q1j2l+aNmTw2YZ4/UY5Mbs4+F +898BfQgOUZrihpEcEeZf+2mkASKtyF4JAB0/ckDuo690rqlsfwKQMsniAujPxA6+ +nx7o+irdpcTTeY3K5n3fMDM= +-----END PRIVATE KEY----- diff --git a/05.Seguridad/mensajefirmado.txt b/05.Seguridad/mensajefirmado.txt new file mode 100644 index 0000000..6bf6f50 --- /dev/null +++ b/05.Seguridad/mensajefirmado.txt @@ -0,0 +1 @@ +{"mensaje": "436f6d70726f62616d6f7320717569656e206669726d612065737465206d656e73616a65", "firma": "6cb45bb9de23b130c4722ab3b3cd26c90010187c27aba71aba415e7167db477df6a4fbbbc01dc1970567dbc999ae184d9953bc296e89c67d"} \ No newline at end of file diff --git a/05.Seguridad/privada_usuario_A.pem b/05.Seguridad/privada_usuario_A.pem new file mode 100644 index 0000000..d82eee5 --- /dev/null +++ b/05.Seguridad/privada_usuario_A.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEAyB4APiFRaxPZ03EDLbxDuihdEa9Bj8gxJHF3OjSDtefRNYDI +M3wf4gSzzNINyHwVqogPTOo/fBoaV4eMIUF+odkAbTuytrSqZc9nYnwBUy3nDiiT +oQ/s1EM1vdPJ5aEl3onfAeRcR+xDonuK+MGwQcBVQEZQK393MPJ0tNyHjfoUZjmz +PaM7OTD6vegcmEx2bD3watNuQ0cibwceQa9cmlZklQXv12wvDRKIbl1eJAsHY0Yw +yXLZtDfNVMh8+1hmCLNiPefQnDU89AwarZiXmFo41e1wfkWuX9G/kga7Ms0F0LRg +/ZYBWhK7eByooTF10ZFwdoyqJpGXYwos6geGbQIDAQABAoIBABePLKEj5AVyp1TU +u7aRMPoEEXzpAJNwUpTDRPGVyCHMwl0Fpcwl400FF7PX0OaW8SgL750zALlYC1zd +qNorb0CXnwy9F/uZhmwJAFdgWPmVcFvC3Cp8iPmuVe/ctKqzj5VE7vu2ikSvZIEH +AWPqzZjYD1FLVdnhHkOlb6bxRYYpws0uhKF8zDw+2lXeydKl+AxOMFQjQsHpFAHA +1335p6F7fRpSINC2+iajy6yV955yM0AQh83izWIRiHJNYHF68u9oWg+2xUZCq1NY +w690yjVAJYqdQ5uFYnEMGjMkjH9lV38AHlP6ixHuNSA996bli4RN87pnpduZS8bg +R7zic4ECgYEAyyqtQPlkUa3hq/OWTcj93NWBJBOZ91s7QBSkGBRb8XG0CsrFFloJ +c6eva/kYFs4Rz4Pna8GnaIaxUH1kyG4oMOJ/mkwdMEpKmt8y45jcm1YRIflCb9yT +XtBb5fJwuBXyG0oWyshyWsC/GI+jrVm3nGlGu58OC4HwtkKfJEr0/K0CgYEA/ChP +awQ+dPtFzI0yrbtBs/lwpU9smSi4OUHJ9PI1/ASUh0k98RpANnTmiw0DtVBORMER +TH2L/jrqjtSTNfmGQz0nPXL7t2VHZsWP3qpo8nPxsz9AiYXPHLsfrGyUg6/ZAwjT +l8OJDBBqvox2IbCEZ0G4nSwwyZHcLRYhYxCCKMECgYEAltqLZpFHUfbAeEMYOY2i +IhVOHJGJY0eUiRJKfa6wTmjU/KZvDRexqPS7pnqAzn4Yb3NLpJFYUp6gjlltOf3B +TfsAMHuPuMmQ98n/KUvZkmWntwgzsoefzWj8s5L+61EwQd8TaWLItmYj/oK5UAAr ++7GX2bxSW20SZOK28+XMXskCgYAXcHfRbtePcDwQw59OXvXAkRNTioqBwjM9v0vS +pSE3iAV2fexwGQyXA07a5h7OH+TmpzvAbHsy6q8bD8+PWN6OKYUYRTP43EVC3GJ/ +RD/1KanyC5MoNXQHK63KDV3Qz+vQSGXC2b5HjM8fX1cr0oi8QHO0yILQeeqJlmEM +IGC5AQKBgDcEbjmei8/hqc0NHt3ZFP/vboabeREXkAt4ipHul9XeTEp3hojQIjPY +ElB4B+qnanHAM7QmYIc9ObQiKPyedZlMkpETm45HBHfzysU7SeHa8GyfbmsGFXgC +Cjx97XRgRo/15PKzMlD/yez9x83IAYHLcRp7eM1V5K9bZLcgOehd +-----END RSA PRIVATE KEY----- \ No newline at end of file diff --git a/05.Seguridad/private_key.pem b/05.Seguridad/private_key.pem new file mode 100644 index 0000000..0aab409 --- /dev/null +++ b/05.Seguridad/private_key.pem @@ -0,0 +1,15 @@ +-----BEGIN PRIVATE KEY----- +MIICXAIBADCCAjUGByqGSM44BAEwggIoAoIBAQCLpc67EBigSTJEBVjl8atX2wIj +tf814ieCCHxvzkLMmq50GUsp3kUlmlZI5SvDkHvfRl85sTDiN2j0CUqsw4Ncebok +4FB4DDEMxf00QLbSgaDywAg7S9Q5eEAP6ENZIRGTCBZ38/JUgw2iiMt3meStySdR +N1EIz1otIB6tgsuQZvwlMURfqf9mg+yiiTqz6JwLynA45EcjyOrM0n9XAIdJz1lz +aKzGzXP+0fDQ1Ke3bh6f4DW2Da/w+hVNpLYta6bj1UiuGOkRhsU8LDo/Sgg0fW/B +yUeAjg2NlMqrO3uhxpUA6ul6q6IIU4TqRWI/98i0qO/krrg9r1IiyZr/0ZiTAh0A +6ZXrZC/1gW6yMVLEEgSpSs1a8zcv9eymC5xdDQKCAQA1SVK03Kq6V+E3yrMXmBYH +7QoP0xYHH6pyHEuQw4RfEoNk0y3AXnpBg92JsjO8ey3rULgWB/wkI/95OofgeQAJ +tlCgsGWOXr0ppJJkvwg9GgsU/genjiNfnXPZ5xvFi9jCYpD14pmH0BmCpHp51Esk +0lLGxWjHE0RZjxYfRNH2hVh3rTrBW/d5nu+c5WyW/aOrHpzg9VrAz7L5g+sxMP2T +yn/wVeMTXAgTcxndBbBQKrV/MZhuJrfN4nS7k4gAckE2NCjIUAnryaiO1ZNwswHd +V2zDPZCN1CTu0HUTJSJxZZhtbw5GW2Cbec6fWk7G2g509OCzHNkIK6LoQK5B+5cW +BB4CHFNvzw3Q5P3tNtrsYuCgw/l3zuLQep9BcP5hxc0= +-----END PRIVATE KEY----- \ No newline at end of file diff --git a/05.Seguridad/private_key_firma.pem b/05.Seguridad/private_key_firma.pem new file mode 100644 index 0000000..5e0ef78 --- /dev/null +++ b/05.Seguridad/private_key_firma.pem @@ -0,0 +1,15 @@ +-----BEGIN PRIVATE KEY----- +MIICXQIBADCCAjYGByqGSM44BAEwggIpAoIBAQC8iI7cae2ByUPzEaHhO2BH+7XS +ioFbY6lPPjX5CXZfw1TVVQE90XEhOUNPuA0t4DaUvMIgrPto1Br78Gyy4mRnEFiA +SXAX2r/MlijGm9f5WcTzW//duOakZ7ffAoEbO39teRK23whSqNLOPJkE/JqcKx5M +dKNF5oa2KXa3kJU6KgRhMcfLHumCVaoF3b1DrVZ4d9y9bSJvWO0gV868d2B+AfjI +3Nrd6WDc7ArD6GM+LqoRCskoZymCoyUZO3d3P56X5yLtOmcbsJtUh+gbChBPJMGX +042sV8gwydro+iQsijo3eHc9p1ufJXlryh9ZG3+XCKoh4mMf7DZYLOEiXYatAh0A +05JYNHr0zvUc4DvJyRDPFylPks3f2PY+REpSewKCAQEAuGHFyGBuAONFn3RP0+Bj +3BFHLsF1KHvkKKbhA8nQCN+u/nyoVzvJp6FYqsGtHffSVa/8vOibIEDkmI7IP/9k +9hhVSmmrF8Jx61b6bHBZHxPmHNZyzKP4UeqL85Y1aGo90u5VcPtYXRjdW2hHuDbJ ++XmmGp0MVqJSmPi96EqGRD51+5xOWpna/z4waxKw33yDLd/yqopGjZx1Qx6lPUUg +EafQ7EqRzzqcKdAfhFIciKiSXruJt1TE/TDBngcAdrGzuc8ULlWDe3YBRpKQxtvG +osShwnJW+z+6rDIQ5W8MAeCwZgM5R0YH/30aHMpEQg5L+t1ON4s9slNM7Q0s0E4k +iwQeAhwgIUzsTphLxt4RemvzXSdQHGhg4c1mgMs9UF8U +-----END PRIVATE KEY----- \ No newline at end of file diff --git a/05.Seguridad/public_key.pem b/05.Seguridad/public_key.pem new file mode 100644 index 0000000..e69de29 diff --git a/05.Seguridad/public_key_firma.pem b/05.Seguridad/public_key_firma.pem new file mode 100644 index 0000000..f78d3f3 --- /dev/null +++ b/05.Seguridad/public_key_firma.pem @@ -0,0 +1,20 @@ +-----BEGIN PUBLIC KEY----- +MIIDRDCCAjYGByqGSM44BAEwggIpAoIBAQC8iI7cae2ByUPzEaHhO2BH+7XSioFb +Y6lPPjX5CXZfw1TVVQE90XEhOUNPuA0t4DaUvMIgrPto1Br78Gyy4mRnEFiASXAX +2r/MlijGm9f5WcTzW//duOakZ7ffAoEbO39teRK23whSqNLOPJkE/JqcKx5MdKNF +5oa2KXa3kJU6KgRhMcfLHumCVaoF3b1DrVZ4d9y9bSJvWO0gV868d2B+AfjI3Nrd +6WDc7ArD6GM+LqoRCskoZymCoyUZO3d3P56X5yLtOmcbsJtUh+gbChBPJMGX042s +V8gwydro+iQsijo3eHc9p1ufJXlryh9ZG3+XCKoh4mMf7DZYLOEiXYatAh0A05JY +NHr0zvUc4DvJyRDPFylPks3f2PY+REpSewKCAQEAuGHFyGBuAONFn3RP0+Bj3BFH +LsF1KHvkKKbhA8nQCN+u/nyoVzvJp6FYqsGtHffSVa/8vOibIEDkmI7IP/9k9hhV +SmmrF8Jx61b6bHBZHxPmHNZyzKP4UeqL85Y1aGo90u5VcPtYXRjdW2hHuDbJ+Xmm +Gp0MVqJSmPi96EqGRD51+5xOWpna/z4waxKw33yDLd/yqopGjZx1Qx6lPUUgEafQ +7EqRzzqcKdAfhFIciKiSXruJt1TE/TDBngcAdrGzuc8ULlWDe3YBRpKQxtvGosSh +wnJW+z+6rDIQ5W8MAeCwZgM5R0YH/30aHMpEQg5L+t1ON4s9slNM7Q0s0E4kiwOC +AQYAAoIBAQCNy1C19UKzD+yxI8Q2yzhgRGoqpm/P43Rfz+fJKgdMDlhcxJMDmuJU +MBmjC+UZEzrIbsYmzKKH9EA6TEDTDrfTh1K/ixwrj9mHouC7qVPP2Lz5qJB074Lh +Nhkj06D+cSZfbXJgZKVbQ42CXl51suYoZaSKnX6ueHz2Wi0QPLmyrst7jLl2kwfR +yBXWw2c9thVDR3m3RIAMsfWfDDzx99quNMozuaM+prjrXT2A+bm5znVty1G2+m91 +RlQPGIhseE3VF5L4P+vswOwe8fdg/noT+eQyK8FVjPypVM5Y51sF7jAwdOPfpkGT +w9dKJALhoz0cUsNbuduYOlc+RF+oZPJj +-----END PUBLIC KEY----- \ No newline at end of file diff --git a/05.Seguridad/publica_usuario_A.pem b/05.Seguridad/publica_usuario_A.pem new file mode 100644 index 0000000..69b4fcb --- /dev/null +++ b/05.Seguridad/publica_usuario_A.pem @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyB4APiFRaxPZ03EDLbxD +uihdEa9Bj8gxJHF3OjSDtefRNYDIM3wf4gSzzNINyHwVqogPTOo/fBoaV4eMIUF+ +odkAbTuytrSqZc9nYnwBUy3nDiiToQ/s1EM1vdPJ5aEl3onfAeRcR+xDonuK+MGw +QcBVQEZQK393MPJ0tNyHjfoUZjmzPaM7OTD6vegcmEx2bD3watNuQ0cibwceQa9c +mlZklQXv12wvDRKIbl1eJAsHY0YwyXLZtDfNVMh8+1hmCLNiPefQnDU89AwarZiX +mFo41e1wfkWuX9G/kga7Ms0F0LRg/ZYBWhK7eByooTF10ZFwdoyqJpGXYwos6geG +bQIDAQAB +-----END PUBLIC KEY----- \ No newline at end of file diff --git a/05.Seguridad/rsa_key_privada.bin b/05.Seguridad/rsa_key_privada.bin new file mode 100644 index 0000000..addb49c --- /dev/null +++ b/05.Seguridad/rsa_key_privada.bin @@ -0,0 +1,30 @@ +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIIFJTBPBgkqhkiG9w0BBQ0wQjAhBgkrBgEEAdpHBAswFAQIXp6qCe+GuiQCAkAA +AgEIAgEBMB0GCWCGSAFlAwQBAgQQCq0d/vmjm8RTvQio4exl1ASCBNA2v3+Pp3e3 +mdrDTPTwR6MaWpAmHyQ1B994AHjHIkC1nnqEukUN6uu6B477dsRyNybDXdrXxHVj +PFZaZrSh95wJM65s0yxMew0YzdZaTCuoYhGM2usbcgdHmII/mD+eDrEawHH/mlAj +0JO30BUmTGtfECAOyXjXQIJDYGUE5Pm/t3s6H3XQ6Fxg4MSYqH8AZziVea+tlFlK +8H+ItCHEFN23deS5woIcYeBwjd/iYmuh7cu2sSq4ilqq09Qi1dTCke0BPhwCxaRy +dfmIQrV9+GO3elM1qKY7Wgpoxz5Isq+VrzTKTgomSKPsd7JmCmwF+lUhBF197/4h +RqU1vCC+dWzWhEgPQSDJswk5P61pzrGGukKncCj8CQsKU4xbdQN/cqmcVGf0VBVd ++Da6geTUUBBI39f1kDV2ZeVhj96xNIBAd6MIkDeB74dQuC62PGxtH8gLdQk4/+kV +bBqGhfmGJ+N93LWhPSJ8b+4PnSUOj9mqMJUyl69prh/WuzAFEPvC8tidmq7k1zAA +gAbclVZKvBByHnSFU2xXbN8OtyCYrsbYTjm/j95tvXdBde/DpxR7S5819pDEM9Ad +2x9bFavSDPj+ofwqUuPCr8nIVQARmtjWvWm7ncKlMi1ic2myYS5O9S+UhNYlJIuc +P5NlOcaGg1rPAaeCfy+ss+rE7P/qaTHLS8g/xo+V1FyhnTyJNydRhuBIQXp1CzGD +ONC6lrTvTzHw4vW94F8Y16xV7Dtov9+anh5WlhJUXVxgG7geojfYSVfWy5MLOLQg +pZoOTCzTAxKs1AXyxYlUjK1I5NPFp7MUiOblef6rKSPaw4WSl60P31otYWyoXQE5 ++ilCr+v1qbWqhexOJRNBCj4gbvD1a1fykHYEOX9gjohMd+Ih272CZD+5aC7ukQYg +OqfDkEC/n3zDQQE5k3N/BCw8g5SCfFBl2NsoHePcRXNxwGH1/pjr28LHaGeNvS3A +IoUTBNpJD0o8YW3l8QV0dsbwLfrSbQbjZ9r4WsWF43SyAStfewHBbFjgj0k4oCcl +vfFUom4MWBQd/abUgXruVEdEM0NtjWUFkNx2fd4VNC2OvKRGxVRG/1j0FCCkmqDK +icSs8fhtCYsvmmE2eXr0rTsCeO8RlV6tddWVX599QTop1cLsJn5dB6xx5Dh1uJqy +VU424RcP/Z9QdLk82wRT/qvXZbfY98cec0yp7++/KKTmUm07STBtIuMUSN5ucuxh +tJetJgdqwujypYFxG/7elJfvfylxjB/o38rS5QOU2833Ei/MO8nqVZiaPUwHtqEE +DDu5kwnWflMMwFGNQlxYrehlLwbbUn4MZeJkDgCSuDC+xzRIk5Cjheaj8cetatPD +1jRCZB/MGB9V09REehSC42puBj2K0T7+9ezKUU5SBnO0BW5mg96O+Dpt7BIqpnbt +m4LzSmKU5ar0bnuyqP01dx8HjCj3KpnZ7AZYoe4vZgFgt+Z+aDo+tWaePYb525mu +UtiJMIaG0o69UPF3G6Cd46PF7ZU0N0qZFci9sjZSrvdVHiF7Z4/8sYKKXtksp/ue +EMbBejbt47vqgZxUuvlv3s/P50Oac8HTXVlSiYDMtLid3FqR/pZ+fC1eFjcBn20W +rP4bKoSLavjAaqW3EcaISBebk6PrMoGJ4A== +-----END ENCRYPTED PRIVATE KEY----- \ No newline at end of file diff --git a/05.Seguridad/textoDesencriptado.txt b/05.Seguridad/textoDesencriptado.txt new file mode 100644 index 0000000..9480086 --- /dev/null +++ b/05.Seguridad/textoDesencriptado.txt @@ -0,0 +1,4 @@ +Hola +Esto es una prueba +Camión +España \ No newline at end of file diff --git a/05.Seguridad/textoEncriptado.txt b/05.Seguridad/textoEncriptado.txt new file mode 100644 index 0000000..2e0aec7 --- /dev/null +++ b/05.Seguridad/textoEncriptado.txt @@ -0,0 +1 @@ +^oqx9Vi)Ug>Ԅ7|cupXr \ No newline at end of file diff --git a/05.Seguridad/textoPlano.txt b/05.Seguridad/textoPlano.txt new file mode 100644 index 0000000..9480086 --- /dev/null +++ b/05.Seguridad/textoPlano.txt @@ -0,0 +1,4 @@ +Hola +Esto es una prueba +Camión +España \ No newline at end of file diff --git a/PROTOCOLO PPT V 1.pdf b/PROTOCOLO PPT V 1.pdf new file mode 100644 index 0000000..c23676e Binary files /dev/null and b/PROTOCOLO PPT V 1.pdf differ diff --git a/README.md b/README.md new file mode 100644 index 0000000..08d0e1e --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +# Programacion_de_servicios_y_procesos_en_Python +Libro Programación de servicios y procesos en Python + +Jose Luis Carnero Sobrino +E-mail: jlcarnerosobrino@gmail.com