gpt4 book ai didi

python - 为 SocketServer 添加 SSL 支持

转载 作者:太空狗 更新时间:2023-10-30 01:43:52 24 4
gpt4 key购买 nike

我有一个基于ThreadingTCPServer 的服务器。现在我想为该服务器添加 SSL 支持。没有 SSL 它工作正常但使用 SSLv3 我无法将客户端连接到服务器,它总是抛出异常:Error 111 Connection Refused。该错误表示该端口上没有 SSL 服务器。

我根据在 Stackoverflow 上找到的示例添加了 SSL 支持。这是我的代码:

服务器:

class BeastServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):

def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True):
SocketServer.BaseServer.__init__(self, server_address,
RequestHandlerClass)
ctx = SSL.Context(SSL.SSLv3_METHOD)
cert = 'server.pem'
key = 'key.pem'
ctx.use_privatekey_file(key)
ctx.use_certificate_file(cert)
self.socket = SSL.Connection(ctx, socket.socket(self.address_family,
self.socket_type))
if bind_and_activate:
#self.server_bind()
#self.server_a

客户:

class Client(object) :

def verbinden (self, ip_) :

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = ssl.wrap_socket(s, cert_reqs=ssl.CERT_REQUIRED,
ssl_version=ssl.PROTOCOL_SSLv3, ca_certs='server.pem')
ssl_sock.connect((ip_, 10012))

return ssl_sock

key 和证书文件是使用开放式 SSL 创建的。我希望有人能告诉我问题出在哪里。

谢谢你的帮助

最好的问候帕特里克

最佳答案

只使用标准库

服务器端:

from SocketServer import TCPServer, ThreadingMixIn, StreamRequestHandler
import ssl

class MySSL_TCPServer(TCPServer):
def __init__(self,
server_address,
RequestHandlerClass,
certfile,
keyfile,
ssl_version=ssl.PROTOCOL_TLSv1,
bind_and_activate=True):
TCPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate)
self.certfile = certfile
self.keyfile = keyfile
self.ssl_version = ssl_version

def get_request(self):
newsocket, fromaddr = self.socket.accept()
connstream = ssl.wrap_socket(newsocket,
server_side=True,
certfile = self.certfile,
keyfile = self.keyfile,
ssl_version = self.ssl_version)
return connstream, fromaddr

class MySSL_ThreadingTCPServer(ThreadingMixIn, MySSL_TCPServer): pass

class testHandler(StreamRequestHandler):
def handle(self):
data = self.connection.recv(4096)
self.wfile.write(data)
#test code
MySSL_ThreadingTCPServer(('127.0.0.1',5151),testHandler,"cert.pem","key.pem").serve_forever()

客户端:

import os
import socket, ssl

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ssl_sock = ssl.wrap_socket(s,
ca_certs="cert.pem",
cert_reqs=ssl.CERT_REQUIRED,
ssl_version=ssl.PROTOCOL_TLSv1)
ssl_sock.connect(('127.0.0.1',5151))
ssl_sock.send('hello ~MySSL !')
print ssl_sock.recv(4096)
ssl_sock.close()

效果不错

关于python - 为 SocketServer 添加 SSL 支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8582766/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com