验证客户端链接的合法性:
如果你想在分布式系统中实现一个简单的客户端链接认证功能,就可以利用 hmac+加盐的方式实现。
import os import hmac import socket secret_key = '顾清秋'.encode('utf-8') sk = socket.socket() sk.bind(('127.0.0.1',9000)) sk.listen() conn,addr = sk.accept() while True: while True: try: random_num = os.urandom(32) # 随机出32位字节 conn.send(random_num) obj = hmac.new(secret_key,random_num) ret = obj.hexdigest() msg = conn.recv(1024).decode('utf-8') if ret == msg: print('链接合法') else: print('链接不合法,将断开连接') conn.close() finally: break sk.close()
import hmac import socket secret_key = '顾清秋'.encode('utf-8') sk = socket.socket() sk.connect(('127.0.0.1',9000)) random_num = sk.recv(1024) obj = hmac.new(secret_key,random_num) ret = obj.hexdigest().encode('utf-8') sk.send(ret) sk.close()
socketserver:
import socketserver class MyServer(socketserver.BaseRequestHandler): def handle(self): self.data = self.request.recv(1024).strip() # self.request 相当于conn print('{} wrote:'.format(self.client_address[0])) print(self.data) self.request.sendall(self.data.upper()) if __name__ == '__main__': socketserver.TCPServer.allow_reuse_address = True server = socketserver.ThreadingTCPServer(('127.0.0.1',9000),MyServer) server.serve_forever()
import socket sk = socket.socket() sk.connect(('127.0.0.1',9000)) sk.send(b'hello') sk.close()