Código fuente Python PSP

main
juanjo 11 months ago
commit 846c54b439

@ -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())

@ -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())

@ -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"))

@ -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)

@ -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()

@ -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()

@ -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)

@ -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)

@ -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")

@ -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)

@ -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")

@ -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")

@ -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()

@ -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")

@ -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

@ -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")

@ -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="")

@ -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)

@ -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)

@ -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()

@ -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()

@ -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()

@ -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()

@ -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)

@ -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')

@ -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')

@ -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()

@ -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()

@ -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"

@ -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!")

@ -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)

@ -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)

@ -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)

@ -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)

@ -0,0 +1,14 @@
import threading
algo = 0
lock = threading.Lock()
lock.acquire()
algo +=1
lock.acquire()
algo += 2
lock.release()
print(algo)

@ -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)

@ -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()

@ -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()

@ -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()

@ -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 <<si no se ha comenzado>>")
t.cancel()

@ -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()

@ -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()

@ -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")

@ -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()")

@ -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)

@ -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")))

@ -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)

@ -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])

@ -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))

@ -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))

@ -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()

@ -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()

@ -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")

@ -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)

@ -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))

@ -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))

@ -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))

@ -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))

@ -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")

@ -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")

@ -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))

@ -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")

@ -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")

@ -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))

@ -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")

@ -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")

@ -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())

@ -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()

@ -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()

@ -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()

@ -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()

@ -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()

@ -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()

@ -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()

@ -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()

@ -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()

@ -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("<<er>>",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("<<er>>",escribirResolucion)
fPPT.mainloop()

@ -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()

@ -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]

@ -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]

@ -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...')

@ -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("</div>")
print(data2[0: indexend])
except UnicodeEncodeError as e:
pass

@ -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)

@ -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)

@ -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))

@ -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"])

@ -0,0 +1 @@
hola, estoy haciendo pruebas con FTP

@ -0,0 +1 @@
hola, estoy haciendo pruebas con FTP

@ -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))

@ -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!")

@ -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)

@ -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)

@ -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)

@ -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)

@ -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/

@ -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)

@ -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()

@ -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 <<pycryptodome>> 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()

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save

Powered by Informatica FP.