我需要在我的服务器和远程 Web 服务之间创建一个安全通道。我将使用带有客户端证书的 HTTPS。我还需要验证远程服务提供的证书。
如何在 urllib2 中使用我自己的客户端证书?
我需要在我的代码中做些什么来确保远程证书是正确的?
最佳答案
因为 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()
关于python - 将客户端证书与 urllib2 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1875052/