使用urllib3忽略证书验证

2024-06-17 10:09:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在对具有自签名证书的私有服务使用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

Tags: inpyselfsendhttprequestlibpackages
2条回答

请尝试以下代码:

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

尝试以这种方式实例化连接池:

HTTPSConnectionPool(self.host, self.port, cert_reqs=ssl.CERT_NONE)

或者这样:

HTTPSConnectionPool(self.host, self.port, cert_reqs='CERT_NONE')

来源:https://github.com/shazow/urllib3/blob/master/test/with_dummyserver/test_https.py


编辑(在看到您的编辑后):

看起来远程主机没有发送证书(可能吗?)。 这是引发异常的代码(来自urllib3):

def match_hostname(cert, hostname):
    """Verify that *cert* (in decoded format as returned by
SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules
are mostly followed, but IP addresses are not accepted for *hostname*.

CertificateError is raised on failure. On success, the function
returns nothing.
"""
    if not cert:
        raise ValueError("empty or no certificate")

所以看起来cert是空的,这意味着self.sock.getpeercert()返回了一个空字符串。

相关问题 更多 >