我需要在我的服务器和远程web服务之间创建一个安全通道。我将使用带有客户端证书的HTTPS。我还需要验证远程服务提供的证书。
发布于 2009-12-10 00:34:40
这是一个看起来相关的bug in the official Python bugtracker,并且有一个建议的补丁。
发布于 2010-12-17 03:05:29
因为alex的答案是一个链接,而该页面上的代码格式很差,所以我将把它放在这里供后人使用:
import urllib2, httplib
class HTTPSClientAuthHandler(urllib2.HTTPSHandler):
def __init__(self, key, cert):
urllib2.HTTPSHandler.__init__(self)
self.key = key
self.cert = cert
def https_open(self, req):
# Rather than pass in a reference to a connection class, we pass in
# a reference to a function which, for all intents and purposes,
# will behave as a constructor
return self.do_open(self.getConnection, req)
def getConnection(self, host, timeout=300):
return httplib.HTTPSConnection(host, key_file=self.key, cert_file=self.cert)
opener = urllib2.build_opener(HTTPSClientAuthHandler('/path/to/file.pem', '/path/to/file.pem.') )
response = opener.open("https://example.org")
print response.read()
发布于 2016-11-26 00:39:04
根据Antoine Pitrou对Hank Gay答案中链接的问题的回应,这可以通过使用包含的ssl
库进行一定程度的简化(从2011年开始):
import ssl
import urllib.request
context = ssl.create_default_context()
context.load_cert_chain('/path/to/file.pem', '/path/to/file.key')
opener = urllib.request.build_opener(urllib.request.HTTPSHandler(context=context))
response = opener.open('https://example.org')
print(response.read())
(Python3代码,但在Python2中也提供了ssl
库)。
load_cert_chain
函数还接受一个可选的password参数,允许加密私钥。
https://stackoverflow.com/questions/1875052
复制相似问题