我正在对具有自签名证书的私有服务使用urllib3.有没有办法让urllib3忽略证书错误并发出请求?

import urllib3
c = urllib3.HTTPSConnectionPool('10.0.3.168', port=9001)
c.request('GET', '/')

当使用以下各项时:

import urllib3
c = urllib3.HTTPSConnectionPool('10.0.3.168', port=9001, cert_reqs='CERT_NONE')
c.request('GET', '/')

出现以下错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3/dist-packages/urllib3/request.py", line 67, in request
    **urlopen_kw)
  File "/usr/lib/python3/dist-packages/urllib3/request.py", line 80, in request_encode_url
    return self.urlopen(method, url, **urlopen_kw)
  File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 415, in urlopen
    body=body, headers=headers)
  File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 267, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "/usr/lib/python3.3/http/client.py", line 1061, in request
    self._send_request(method, url, body, headers)
  File "/usr/lib/python3.3/http/client.py", line 1099, in _send_request
    self.endheaders(body)
  File "/usr/lib/python3.3/http/client.py", line 1057, in endheaders
    self._send_output(message_body)
  File "/usr/lib/python3.3/http/client.py", line 902, in _send_output
    self.send(msg)
  File "/usr/lib/python3.3/http/client.py", line 840, in send
    self.connect()
  File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 103, in connect
    match_hostname(self.sock.getpeercert(), self.host)
  File "/usr/lib/python3/dist-packages/urllib3/packages/ssl_match_hostname/__init__.py", line 32, in match_hostname
    raise ValueError("empty or no certificate")
ValueError: empty or no certificate

使用cURL我能够从服务中得到预期的响应

$ curl -k https://10.0.3.168:9001/
Please read the documentation for API endpoints

推荐答案

请try 以下代码:

import urllib3
c = urllib3.HTTPSConnectionPool('10.0.3.168', port=9001, cert_reqs='CERT_NONE',
                                assert_hostname=False)
c.request('GET', '/')

Setting assert_hostname to False will disable SSL hostname verification

Python-3.x相关问答推荐

在Python中从mySQL获取多行

如何在python中有效地使用多处理和pytube库来加快下载速度?

将列表项的极列水平分解为新列

如何计算累积几何平均数?

匹配语句NaN

Python BeautifulSoup:在 Select 语句中排除其他标签

RGB 图像中最主要的 colored颜色 - OpenCV / NumPy / Python

Generic[T] 基类 - 如何从实例中获取 T 的类型?

如何将 SimpleGUI 与 Python 2.7 和 3.0 shell 集成

Python 3 与 Python 2 映射行为

Tensorflow:ImportError:libcudnn.so.7:无法打开共享对象文件:没有这样的文件或目录

Python中的多行日志(log)记录

如何使用 python 库连接到 poloniex.com websocket api

无论如何我可以在 Google colaboratory 中下载文件吗?

为什么 string.maketrans 在 Python 3.1 中不起作用?

导入父目录进行简要测试

具有不均匀间隙的 Python 范围

三个参数的reduce函数

什么是ANSI_X3.4-1968编码?

TypeError:无法实例化类型元组;使用 tuple() 代替