サーバーとリモート Web サービスの間に安全なチャネルを作成する必要があります。クライアント証明書で HTTPS を使用します。また、リモート サービスによって提示された証明書を検証する必要もあります。
urllib2 で自分のクライアント証明書を使用するにはどうすればよいですか?
リモート証明書が正しいことを確認するには、コードで何をする必要がありますか?
サーバーとリモート Web サービスの間に安全なチャネルを作成する必要があります。クライアント証明書で HTTPS を使用します。また、リモート サービスによって提示された証明書を検証する必要もあります。
urllib2 で自分のクライアント証明書を使用するにはどうすればよいですか?
リモート証明書が正しいことを確認するには、コードで何をする必要がありますか?
アレックスの答えはリンクであり、そのページのコードは適切にフォーマットされていないため、後世のためにこれをここに配置します。
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 バグトラッカーのバグです。
Hank Gay's answer にリンクされている問題に対する Antoine Pitrou の回答によると、これは含まれている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())
(Python 3 コードですが、ssl
ライブラリは Python 2 でも利用できます)。
このload_cert_chain
関数は、オプションのパスワード パラメータも受け入れ、秘密鍵を暗号化できるようにします。