作者:wuyanting67412 | 来源:互联网 | 2023-06-24 15:19
1.客户端的链接合法性验证:恶意的登录:扫描端口(0-65535) tcp没有做登录客户端时:使用hmac生成对随机字符串的摘要importosimporthmacimportso
1.客户端的链接合法性验证:
恶意的登录:扫描端口(0-65535)
tcp没有做登录客户端时:
使用hmac生成对随机字符串的摘要
import os
import hmac
import socket
def auth(conn):
msg = os.urandom(32) #生成一个随机字符串
conn.send(msg) #发送到客户端
result = hmac.new(secret_key,msg) #处理这个字符串,得到一个结果
# print(result)
client_digest = conn.recv(1024) # 接收客户端返回的处理结果
if result.hexdigest() == client_digest.decode('utf-8'):
print('合法的链接') #对比成功可以继续通信
return True
else:
print('非法链接')
return False
secret_key = b'123'
sk = socket.socket()
sk.bind(('192.168.16.33',8088))
sk.listen()
conn,addr = sk.accept()
# print(conn)
if auth(conn):
print(conn.recv(1024))
conn.close()
else:
conn.close()
sk.close()
import hmac
import socket
sk = socket.socket()
sk.connect(('192.168.16.33',8088))
def auth(sk):
# print(sk)
msg = sk.recv(1024)
result = hmac.new(key,msg)
# print(result)
res = result.hexdigest()
sk.send(res.encode('utf-8'))
key = b'123'
auth(sk)
sk.send(b'upload')
sk.close()
2:socketserver模块;
tcp协议,一个服务端同时与对个客户端同时通信
import socketserver
class Myserver(socketserver.BaseRequestHandler):
def handle(self):
cOnn= self.request
while True:
conn.send(b'abc')
print(conn.recv(1024))
server = socketserver.ThreadingTCPServer(('192.168.16.33',8088),Myserver)
server.serve_forever()
import socket
sk = socket.socket()
sk.connect(('192.168.16.33',8088))
while True:
ret = sk.recv(1024)
print(ret)
sk.send(b'byebye')
sk.close()