SocketServer模块,hmac模块验证client合法性

hmac模块:


1.模块初识:

import hmac
# h = hmac.new() #括号里要给它连个bytes类型,一个是自定义的secret_key,一个是你想进行加密的bytes
# 密文 = h.digest()
# hmac.compare_digest() #括号内传另外一个密文,看是否相等 h = hmac.new(b'secret',b'')
digest = h.digest()
print(digest)
#>>>> b'\xa4<\r\xf8\xec0\x7f\x8ao\xec\xa7(\xf7[t\xfb' h = hmac.new(b'secret',b'')
digest2 = h.digest()
print(hmac.compare_digest(digest,digest2)) #返回true

hmac模块初识

2.使用hmac模块,验证client端的合法性

import os
import hmac
import socket
secret_key = b'wwl'
sk = socket.socket()
sk.bind(('127.0.0.1',8080))
sk.listen()
def check_client(conn):
msg = os.urandom(32)
conn.send(msg)
h = hmac.new(secret_key,msg)
digest = h.digest()
client_digest = conn.recv(1024)
return hmac.compare_digest(digest,client_digest) conn,addr = sk.accept()
res = check_client(conn)
if res:
print('合法的客户端')
conn.close()
else:
print('不合法的客户端')
conn.close()
sk.close()

server端-hmac

import socket
import hmac secret_key = b'wwl111'
sk = socket.socket()
sk.connect(('127.0.0.1',8080)) msg = sk.recv(1024)
h = hmac.new(secret_key,msg)
client_digest = h.digest()
sk.send(client_digest)
sk.close()

client端-hamc

socketserver模块:


解读socketserver源码 —— http://www.cnblogs.com/Eva-J/p/5081851.html

socketserver模块可以开启server端的多线程,让多个client端访问server端:

import socketserver
class MyServer(socketserver.BaseRequestHandler):
def handle(self):#原来socket写的程序里所有和conn有关的操作,都挪到handle方法里
#self.request#相当于conn #一旦客户端断开连接了,handle方法也应该结束
while True:
msg = self.request.recv(1024).decode('utf-8')
if msg == 'q':break
print(msg)
info = input('%s>>>> '%msg[:2])
self.request.send(info.encode('utf-8')) if __name__ == '__main__':
server = socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyServer)
server.serve_forever()

server端-socketserver

import socket
sk = socket.socket()
sk.connect(('127.0.0.1',8080))
while True:
msg = input('>>>> ')
if msg == 'q':
break
sk.send(msg.encode('utf-8'))
ret = sk.recv(1024).decode('utf-8')
print(ret)
sk.close()

client端-socketserver

上一篇:Linux常用的基本命令14


下一篇:第七届蓝桥杯javaB组真题解析-凑算式(第三题)