首页 > 解决方案 > Python TLS 客户端代码给出 Wrap Socket 意外关键字错误

问题描述

我正在尝试使用以下客户端代码连接到使用 TLS 的服务器。(AES 256)

from socket import create_connection
import ssl
from ssl import SSLContext, PROTOCOL_TLS_CLIENT


hostname='MyHost'
ip = '10.98.1.1'
port = 11900
context = SSLContext(PROTOCOL_TLS_CLIENT)
context.load_verify_locations('client.pem')

with create_connection((ip, port)) as client:
    # with context.wrap_socket(client, server_hostname=hostname) as tls:
    with context.wrap_socket(client, ca_certs="ca.key", cert_reqs=ssl.CERT_REQUIRED, certfile="client.pem", keyfile="client.key") as tls:
        print(f'Using {tls.version()}\n')
        tls.sendall(b'Hello, world')

        data = tls.recv(1024)
        print(f'Server says: {data}')

我在运行它时收到以下错误。在 Python 3.6/3.7 和 3.9 中

Traceback (most recent call last):
  File "main.py", line 14, in <module>
    with context.wrap_socket(client, ca_certs="ca.key", cert_reqs=ssl.CERT_REQUIRED, certfile="client.pem", keyfile="client.key") as tls:
TypeError: wrap_socket() got an unexpected keyword argument 'ca_certs'

根据我所做的谷歌搜索,这似乎是 Python 3.7 中的一个中断,但我不明白为什么代码甚至在 Python 3.6 中都不起作用。Python有问题还是我错误地使用了函数调用?


以下是使用 +TomerPlds 解决方案的更新工作代码

from socket import create_connection
import ssl
from ssl import SSLContext, PROTOCOL_TLS_CLIENT


hostname='MyHost'
ip = '10.98.1.1'
port = 11900
context = SSLContext(PROTOCOL_TLS_CLIENT)
context.load_verify_locations('ca.pem')

with create_connection((ip, port)) as client:
    # with context.wrap_socket(client, server_hostname=hostname) as tls:
    with context.wrap_socket(client, server_hostname=hostname) as tls:
        print(f'Using {tls.version()}\n')
        tls.sendall(b'Hello, world')

        while(True):
            data = tls.recv(1024000000)
            print(f'Server says: {data}')

标签: pythonpython-3.xsslpython-requests

解决方案


出现意外关键字错误的原因是 SSLContext.wrap_socket 没有 ca_cert 参数,正如您在文档中看到的那样。相反,您可以使用SSLContext.load_verify_locations来加载 CA 证书和客户端证书。

顺便说一句,看起来您混合了 ssl.wrap_socket 和 SSLContext.wrap_socket 的参数,这就是错误参数的来源。


推荐阅读