如何通过 Python3 请求信任 badssl.com 的自签名证书

How to trust self signed certificate of badssl.com with Python3 requests

import requests

certificate = "-----BEGIN CERTIFICATE-----\nMIIDeTCCAmGgAwIBAgIJAIb7Tcjl3Q8YMA0GCSqGSIb3DQEBCwUAMGIxCzAJBgNV\nBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNp\nc2NvMQ8wDQYDVQQKDAZCYWRTU0wxFTATBgNVBAMMDCouYmFkc3NsLmNvbTAeFw0x\nNjA4MDgyMTE3MDVaFw0xODA4MDgyMTE3MDVaMGIxCzAJBgNVBAYTAlVTMRMwEQYD\nVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNpc2NvMQ8wDQYDVQQK\nDAZCYWRTU0wxFTATBgNVBAMMDCouYmFkc3NsLmNvbTCCASIwDQYJKoZIhvcNAQEB\nBQADggEPADCCAQoCggEBAMIE7PiM7gTCs9hQ1XBYzJMY61yoaEmwIrX5lZ6xKyx2\nPmzAS2BMTOqytMAPgLaw+XLJhgL5XEFdEyt/ccRLvOmULlA3pmccYYz2QULFRtMW\nhyefdOsKnRFSJiFzbIRMeVXk0WvoBj1IFVKtsyjbqv9u/2CVSndrOfEk0TG23U3A\nxPxTuW1CrbV8/q71FdIzSOciccfCFHpsKOo3St/qbLVytH5aohbcabFXRNsKEqve\nww9HdFxBIuGa+RuT5q0iBikusbpJHAwnnqP7i/dAcgCskgjZjFeEU4EFy+b+a1SY\nQCeFxxC7c3DvaRhBB0VVfPlkPz0sw6l865MaTIbRyoUCAwEAAaMyMDAwCQYDVR0T\nBAIwADAjBgNVHREEHDAaggwqLmJhZHNzbC5jb22CCmJhZHNzbC5jb20wDQYJKoZI\nhvcNAQELBQADggEBALW4pad52T7VNw2nFMjPH98ZJNAQQgWyr3H2KlZN6IFGsonO\nnCC/Do8BPx6BnP3PFwovWMat1VvnRRoC8lw/30eEazWqBRGZWPz6LHTE3DNBJdc8\nxz6mh8q9RJX/PAj+YYGNElTu6qj49YT0BEhMF4U+dTQ0G8y3x4WNfiu9pGqyrp8d\nAzeidMfQ/pU01PpoPTDLvRDNkmMsABNE1fXBfJxDDGwfq1xY1j23Fm6BolwZC2y7\nn19h+vMYVWbGoovrf2/ibTvtcTyfDop7gl5Yy3OncZxokFj21rUZpLgx9ea4a9z3\nFzEz5ufynq03RhHTE1eu+gDzMEF0GNhGGsKqeA4=\n-----END CERTIFICATE-----\n"

import tempfile
import os

cert = tempfile.NamedTemporaryFile(mode='w', delete=False)
cert.write(certificate)
cert.close()

cert = cert.name
response = requests.get("https://self-signed.badssl.com", verify=cert)

以上脚本失败:

requests.exceptions.SSLError: HTTPSConnectionPool(host='self-signed.badssl.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')])")))

有趣的是,我可以让 Python3 请求信任其他自签名证书,但不能信任这个。 我在这里做错了什么吗?或者 self-signed.badssl.com 证书有什么特殊之处?

原来self-signed.badssl.com过期了。出于某种原因,Python3 请求不信任作为 verify arg 传递的链,以防其中有过期的证书。