我正在尝试从 Linux 机器上运行的 Python/requests 连接到使用内部 CA 的公司内部网 HTTPS 服务器。我有一个 .pem 文件,其中包含我们的证书(4096 位 RSA、CSSM_KEYUSE_VERIFY、CA = true)。
我将其放入 /usr/share/ca-certificates
的子文件夹中,并使用 sudo dpkg-reconfigure ca-certificates
将其集成到系统中。
在requests documentation ,我发现:
You can pass verify the path to a CA_BUNDLE file or directory with certificates of trusted CAs … If verify is set to a path to a directory, the directory must have been processed using the c_rehash utility supplied with OpenSSL.
我相信(但不确定)/etc/ssl/certs
满足这个条件。
现在,我尝试了各种请求:
requests.get(download_url)
# throws requests.exceptions.SSLError: ("bad handshake: Error([
# ('SSL routines', 'ssl3_get_server_certificate',
# 'certificate verify failed')],)",)
requests.get(download_url, verify = False)
# works, but is obviously bad (and spits out a warning)
requests.get(download_url, verify = pem_file_path)
# same SSLError as above (option shows no effect)
requests.get(download_url, cert = pem_file_path)
requests.get(download_url, cert = '/etc/ssl/certs')
# both throw OpenSSL.SSL.Error: [
# ('PEM routines', 'PEM_read_bio', 'no start line'),
# ('SSL routines', 'SSL_CTX_use_PrivateKey_file', 'PEM lib')]
requests.get(download_url, verify = '/etc/ssl/certs')
# Finally, this raises an unprintable exception:
# requests.exceptions.SSLError: <exception str() failed>
实际上,using self-signed certificates with requests in python看起来它可以描述相同的问题(但尚未回答)。
最佳答案
感谢@stark,我发现问题是我的证书文件已过期。使用正确的最新证书(即使是 DER 格式,带有 .cer 扩展名),以下语法现在可以使用:
requests.get(download_url, verify = cer_file_path)
关于python - 向请求添加单个证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38182773/