使用超时时 Python OpenSSL 连接握手失败

标签 python openssl

在启动与任何主机的 TLS 连接时,我看到一个奇怪的问题。如果我没有在套接字上设置任何超时,它工作正常。如果我这样做,它会在 超时之前用 OpenSSL.SSL.WantReadError 中断。例如,如果我将超时设置为 100,无论如何它都会在一秒后中断。

现在我使用一种解决方法,即设置连接超时,然后在握手之前将其删除。我该如何解决这个问题以遵守超时?

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)

ctx = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_METHOD)
ctx.set_options(OpenSSL.SSL.OP_NO_SSLv2 | OpenSSL.SSL.OP_NO_SSLv3)
ctx.set_verify(OpenSSL.SSL.VERIFY_NONE, lambda _a, _b, _c, _d, _e: None)
conn = OpenSSL.SSL.Connection(ctx, s)
conn.set_tlsext_host_name(hostname.encode('utf-8'))
conn.connect((ip, port))

s.settimeout(None)

try:
    conn.do_handshake()
except OpenSSL.SSL.WantReadError:
    # this happens on every connection

最佳答案

解决方法:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setblocking(1)

关于使用超时时 Python OpenSSL 连接握手失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26540429/

相关文章:

python - 如何在 upload_video.py 中指定多行描述

python - 创建 Python 命令行应用程序

linux - 如何在 Linux 中不使用 make 升级 OpenSSL

go - Paho GO 客户端无法连接到 Broker

python - 在Python中定义默认类属性?

python - 如何将 Python 字典附加到 Pandas DataFrame,将键与列名匹配

python - 在 Python 中评估为相等的非等效变量

c - 椭圆曲线例程 :o2i_ECPublicKey:passed a null parameter:ec_asn1. c:1271:

python - 在 Python 中加密私钥

c - 在 Asterisk 中使用 libwebsockets + ssl 在创建 ssl 上下文时出错 140A90A1 :lib(20):func(169):reason(161)