python - 将客户端证书与 urllib2 一起使用

标签 python ssl certificate urllib2 mutual-authentication

我需要在我的服务器和远程 Web 服务之间创建一个安全通道。我将使用带有客户端证书的 HTTPS。我还需要验证远程服务提供的证书。

  1. 如何在 urllib2 中使用我自己的客户端证书?

  2. 我需要在我的代码中做些什么来确保远程证书是正确的?

最佳答案

因为 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/

相关文章:

python - 在 seaborn 情节中更改图例标题大小的优雅方法?

python - 如何跟踪Scrapy中已抓取的域名数量

ruby-on-rails - 有没有办法完全免费使用 letsencrypt 在 heroku-godaddy 上设置 SSL?

elasticsearch - elasticsearch-certutil 创建的证书在生产中不可用?

python - Scrapy,从第二组链接中抓取页面

python 分割和反转文本文件

android - 认证问题,所以我想信任所有应用程序

java - 具有用户名和登录名的用户 session

kubernetes - 续订Kubernetes丛集凭证

certificate - javafx 2.1 中的签名者证书