在python

时间:2016-01-13 13:03:05

标签: python-2.7 https openssl python-requests

情况: 目标站点(例如,前导URL,例如https://my-pre-prod-site.com/login)正在使用自签名证书。 在浏览器中,可以通过https访问该站点而不会出现任何问题(通过在浏览器中将证书添加到信任库来禁止自签名证书警告)

问题陈述: 使用请求对目标站点进行get调用的简单python脚本在不同情况下失败,并出现以下任一错误:

  

requests.exceptions.SSLError:[Errno 0] _ssl.c:344:错误:00000000:lib(0):func(0):reason(0)

  

requests.exceptions.SSLError:[SSL:CERTIFICATE_VERIFY_FAILED]证书验证失败(_ssl.c:590)   使用的简单脚本(在python提示符下)是:

import requests
res = requests.get('https://my-pre-prod-site.com/login')

**已经尝试过的事情**

  1. NOT 想要跳过ssl验证。因此,verify = false不适合我。
  2. 我已经使用了以下相同的错误
  3. res = requests.get('https://my-pre-prod-site.com/login', verify = os.path.join(os.getcwd(),'test.pem')其中test.pem是通过按以下顺序连接以下命令的输出而创建的pem文件:

      

    openssl rsa -in~ / Desktop / CertPath / private.key -check

      

    openssl x509 -pubkey -noout -in~ / Desktop / CertPath / certificate.pem

    脚本从〜/ Desktop / CertPath运行,因此getcwd()提供了证书的正确路径。

    1. 我尝试了另一个test.pem文件,其中连接顺序被颠倒了。它仍然会抛出同样的错误。
    2. 尝试单独(单独)传递持有公钥的.pem文件和持有私钥的.key文件,并且结果与错误相同。
    3. 有帮助的环境详细信息

      操作系统 - ElCapitan Mac
      请求 - 2.9.0
      Python - 2.7.10
      Python使用的OpenSSL - 'OpenSSL 0.9.8zg 2015年7月14日'

      注意 - openssl版本似乎不是问题。因为即使使用openssl的更新版本,错误也是相同的 - 在Ubuntu上测试 Python 2.6使用Openssl 1.x

2 个答案:

答案 0 :(得分:4)

这个问题已经过时了,如果有人想知道这里。

您将私钥和公钥放在test.pem中。这是错的。验证参数需要的是它可以信任的证书。

res = requests.get('https://my-pre-prod-site.com/login', verify = os.path.join(os.getcwd(),'test.pem')

test.pem应该包含所有可信证书的列表。但是,您在test.pem中提供的是您的公钥和私钥。您的〜/ Desktop / CertPath / certificate.pem文件本身应该进入它。

试试这个:

res = requests.get('https://my-pre-prod-site.com/login', verify = '~/Desktop/CertPath/certificate.pem')

答案 1 :(得分:-1)

specify certificate for SSL verification你可以使用:

requests.get('https://my-pre-prod-site.com/login', cert=os.path.join(os.getcwd(),'test.pem'))