python - 向请求添加单个证书

标签 python ssl python-requests

我正在尝试从 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/

相关文章:

python - 这个 Python 模拟补丁有什么问题?

ios - 在 AFNetworking 中支持 SNI

java - 使用 java 的 Websphere MQ SSL 连接

node.js - Node : PORT 443 requires elevated privileges error

python - 在 Python 2.7 中执行 http 请求时使用 'while True'

Python for循环查询

python - 使用多个接受参数的 fixture 进行参数化测试

python - 按 Pandas 数据框分组并选择序列中的最大值

python - 如何使用 python zeep 进行重试处理?我正在使用请求重试 session ,但未处理异常

Python requests_toolbelt MultipartEncoder 文件名