如何创建Python安全websocket客户端请求?

Rav*_*and 5 openssl tornado websocket python-3.x azure-web-app-service

我的Python安全websocket客户端代码给我例外如下:

[SSL:CERTIFICATE_VERIFY_FAILED]证书验证失败(_ssl.c:748)

我已经创建了我的私有证书和签名证书,但我无法使用Python脚本连接到它,如下所示:

import json
from websocket import create_connection


class subscriber:
   def listenForever(self):
   try:
      # ws = create_connection("wss://localhost:9080/websocket")
      ws = create_connection("wss://nbtstaging.westeurope.cloudapp.azure.com:9090/websocket")
      ws.send("test message")
      while True:
          result = ws.recv()
          result = json.loads(result)
          print("Received '%s'" % result)

      ws.close()
  except Exception as ex:
      print("exception: ", format(ex))


try:
    subscriber().listenForever()
except:
    print("Exception occured: ")
Run Code Online (Sandbox Code Playgroud)

我在python中使用龙卷风的https/wss服务器脚本如下:

import tornado.web
import tornado.websocket
import tornado.httpserver
import tornado.ioloop
import os
import ssl

ssl_root = os.path.join(os.path.dirname(__file__), 'ssl1_1020')


class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def check_origin(self, origin):
        return True

    def open(self):
        pass

    def on_message(self, message):
        self.write_message("Your message was: " + message)
        print("message received: ", format(message))

    def on_close(self):
        pass


class IndexPageHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("index.html")


class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
           (r'/', IndexPageHandler),
           (r'/websocket', WebSocketHandler),
        ]

        settings = {
            'template_path': 'templates'
        }
        tornado.web.Application.__init__(self, handlers, **settings)


ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_ctx.load_cert_chain(ssl_root+"/server.crt",
                    ssl_root + "/server.pem")


if __name__ == '__main__':
    ws_app = Application()
    server = tornado.httpserver.HTTPServer(ws_app, ssl_options=ssl_ctx,)
    server.listen(9081, "0.0.0.0")
    print("server started...")
    tornado.ioloop.IOLoop.instance().start()
Run Code Online (Sandbox Code Playgroud)

用于创建SSL签名证书的步骤:

openssl genrsa -des3 -out server.key 1024
openssl rsa -in server.key -out server.pem
openssl req -new -nodes -key server.pem -out server.csr
openssl x509 -req -days 365 -in server.csr -signkey server.pem -out server.crt
Run Code Online (Sandbox Code Playgroud)

Or *_*uan 8

For me, ignoring the errors is not an options, I had to use my self signed certificate because of SSL pinning in a complex IoT environment:

import asyncio
import pathlib
import ssl
import websockets

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
localhost_pem = pathlib.Path(__file__).with_name("localhost.pem")
ssl_context.load_verify_locations(localhost_pem)

async def hello():
    uri = "wss://localhost:8765"
    async with websockets.connect(
        uri, ssl=ssl_context
    ) as websocket:
        name = input("What's your name? ")

        await websocket.send(name)
        print(f"> {name}")

        greeting = await websocket.recv()
        print(f"< {greeting}")

asyncio.get_event_loop().run_until_complete(hello())
Run Code Online (Sandbox Code Playgroud)

发现它这里的WebSocket的回购的例子文件夹。

聚苯乙烯

我改变它SSLContext(ssl.PROTOCOL_TLS_CLIENT),以SSLContext(ssl.PROTOCOL_TLSv1_2)让它工作


Rav*_*and 6

最后我找到了解决方案,我更新了python客户端脚本,同时连接到安全的Web套接字url以忽略cert请求,如下所示:

 ws = websocket.WebSocket(sslopt={"cert_reqs": ssl.CERT_NONE})
 ws.connect("wss://xxx.com:9090/websocket")
Run Code Online (Sandbox Code Playgroud)


小智 6

如果将来有人好奇为什么 wss python 服务器失败是因为龙卷风文档中的这一点:

\n\n
\n

当使用带有自签名证书的安全 Websocket 连接 (wss://) 时,浏览器的连接可能会失败,因为它想要显示 \xe2\x80\x9caccept 此证书\xe2\x80\x9d 对话框,但无处可去来展示它。您必须首先使用相同的证书访问常规 HTML 页面以接受它,然后 Websocket 连接才会成功。

\n
\n