- 需求:加载ECC证书,与服务端通过urllib2 实现https双向认证。
网上找了一圈,未找到能符合预期的,chatgpt之前给的也有问题。
经过多轮迭代询问,还是chatgpt 3.5写的代码,亲测可用。
给chatGPT的promot:
你是一名linux和python专家,同时也是一名网络通信专家。
在建立https双向认证时,可以通过curl命令实现,比如:curl --cacert ./tls-ca.pem --cert ./tls-cert.pem --key ./tls-key.pem -X GET https://xxxx.xxx
请用python2.7实现上面等效的功能
import urllib
import urllib2
import ssl
url = 'https://xxxxxx'
params = {
'token': 'xxx',
'ak': 'xx',
'version': 'xx'
}
# Path to your certificate and key files
cert_file = './tls-cert.pem'
key_file = './tls-key.pem'
# Path to your CA certificate file
ca_certs = './tls-ca.pem'
# Create an SSL context
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
# Load the certificate and key
context.load_cert_chain(certfile=cert_file, keyfile=key_file)
# Set the CA certificate file
context.load_verify_locations(cafile=ca_certs)
# Create an HTTPS opener with SSL support
opener = urllib2.build_opener(urllib2.HTTPSHandler(context=context))
# Encode parameters and append them to the URL
#url = '{}?{}'.format(url, urllib.urlencode(params))
# Make the GET request
response = opener.open(url)
# Read and print the response
print(response.read())
# Close the connection
response.close()