【发布时间】:2021-07-24 07:42:22
【问题描述】:
我正在尝试使用 following 客户端代码连接到使用 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'
根据Googling I did,这似乎是 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}')
【问题讨论】:
标签: python python-3.x ssl python-requests