问题描述
我正在使用请求连接到 RESTful API.我想要访问的服务器使用带有自签名证书的 ssl.
I'm using Requests to connect to a RESTful API. The server I would like to reach use ssl with self-singed certificate.
cafile = "gateway.pem"
r = requests.get(request, auth=('admin', 'password'), verify=cafile)
问题是我收到主机名不匹配的 SSLError.应该有一种方法可以在不禁用证书验证的情况下禁用主机名检查,就像在许多 Java 实现中一样,但我在 python 中找不到如何处理请求的方法.
the problem is I'm getting SSLError of hostname mismatch.there should be a way to disable the hostname checking without disabling certificate validation, as in many java implementations, but I can't find how to do it with requests in python.
堆栈跟踪:
Traceback (most recent call last):
File "<pyshell#43>", line 1, in <module>
r = requests.get(request, auth=("admin", "password"), verify='gateway.pem')
File "C:\Python27\lib\site-packages\requests-2.0.0-py2.7.egg\requests\api.py", line 55, in get
return request('get', url, **kwargs)
File "C:\Python27\lib\site-packages\requests-2.0.0-py2.7.egg\requests\api.py", line 44, in request
return session.request(method=method, url=url, **kwargs)
File "C:\Python27\lib\site-packages\requests-2.0.0-py2.7.egg\requests\sessions.py", line 357, in request
resp = self.send(prep, **send_kwargs)
File "C:\Python27\lib\site-packages\requests-2.0.0-py2.7.egg\requests\sessions.py", line 460, in send
r = adapter.send(request, **kwargs)
File "C:\Python27\lib\site-packages\requests-2.0.0-py2.7.egg\requests\adapters.py", line 358, in send
raise SSLError(e)
SSLError: hostname '10.76.92.70' doesn't match u'lital.com'
这是怎么做到的?
推荐答案
Requests 不允许直接这样做,但是您可以提供使用底层 urllib3
功能的自定义传输适配器.请求文档中介绍了传输适配器的使用.
Requests doesn't allow this directly, however you can provide a custom transport adapter which uses the features of the underlying urllib3
. The usage of transport adapters is covered in the requests documentation.
此代码未经测试,但应该可以工作.
This code is not tested, but should work.
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager
# Never check any hostnames
class HostNameIgnoringAdapter(HTTPAdapter):
def init_poolmanager(self, connections, maxsize, block=False):
self.poolmanager = PoolManager(num_pools=connections,
maxsize=maxsize,
block=block,
assert_hostname=False)
# Check a custom hostname
class CustomHostNameCheckingAdapter(HTTPAdapter):
def cert_verify(self, conn, url, verify, cert):
# implement me
host = custom_function_mapping_url_to_hostname(url)
conn.assert_hostname = host
return super(CustomHostNameCheckingAdapter,
self).cert_verify(conn, url, verify, cert)
assert_hostname
参数的详细工作如下:如果 None
使用 URL 中的主机名,如果 False
禁止主机名检查,如果自定义字符串对此字符串进行验证.
In detail the assert_hostname
param works as follows:If None
use the hostname from the URL, if False
suppress hostname checking, if a custom string validate against this string.
这篇关于如何禁用请求中的主机名检查python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!