使用 SocketServer.TCPServer 通过 SSL 的 TCP 服务器 [英] TCP-Server over SSL using SocketServer.TCPServer
问题描述
我想为现有的基于 SocketServer.TCPServer 类的 TCP 服务器添加 ssl 支持.所以我覆盖了 TCPServer 类的默认构造函数并添加了 ssl.wrap_socket(...)-call:
i want to add ssl-support to an existing TCP-server which is based on the SocketServer.TCPServer class. So i overrode the default constructor of the TCPServer class and added the ssl.wrap_socket(...)-call:
class MyTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True):
# See SocketServer.TCPServer.__init__
# (added ssl-support):
SocketServer.BaseServer.__init__(self, server_address,
RequestHandlerClass)
self.socket = ssl.wrap_socket(
socket.socket(self.address_family, self.socket_type),
server_side=True,
certfile='cert.pem'
)
if bind_and_activate:
self.server_bind()
self.server_activate()
启动服务器时,没有发生错误.所以我也修改了我的简单测试客户端以支持 ssl:
When starting the server, no error occurrs. So i modified my simple test-client to support ssl, too:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock = ssl.wrap_socket(s)
sock.connect(('192.168.1.1', 54321))
再次没有错误发生,但是连接调用被阻塞了.使用 Ctrl+C 关闭客户端时,显示以下内容:
Again no error occurrs, but the connect-call is blocking. When closing the client using Ctrl+C it shows the following:
Traceback (most recent call last):
File "exampleClient.py", line 10, in <module>
sock.do_handshake()
File "/usr/lib/python2.6/ssl.py", line 293, in do_handshake
self._sslobj.do_handshake()
KeyboardInterrupt
所以在连接时 do_handshake 是阻塞的.有谁知道如何解决这个问题?我只想使用加密的 TCP 连接 :)
So the do_handshake is blocking when connecting. Does anyone knows how to fix the problem? I simply want to use an encrypted TCP-connection :)
推荐答案
好的,我找到了解决方案.现在我使用类似的东西this 使用 OpenSSL 包:
Ok, i found a solution. Now i use something similar to this using the OpenSSL-package:
MyTCPServer-Constructor 内部:
Inside the MyTCPServer-Constructor:
SocketServer.BaseServer.__init__(self, server_address, RequestHandlerClass)
ctx = SSL.Context(SSL.SSLv23_METHOD)
cert = 'cert.pem'
ctx.use_privatekey_file(cert)
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_activate()
在 StreamRequestHandler 的设置方法中:
And in the setup-method of the StreamRequestHandler:
self.connection = self.request
self.rfile = socket._fileobject(self.request, "rb", self.rbufsize)
self.wfile = socket._fileobject(self.request, "wb", self.wbufsize)
这似乎工作正常:-)
这篇关于使用 SocketServer.TCPServer 通过 SSL 的 TCP 服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!