关于python https摘要认证时遇到的一个问题(URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed)

在项目中有一地址需要摘要认证访问方式,但是脚本一直提示 证书验证失败,如下细心

urllib2.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)>

但是使用其他同事的ubuntu就可以,最终发现是python 版本不同 导致,网上找到了一个大神的方法 记录一下

Python 升级到 2.7.9 之后引入了一个新特性,当使用urllib.urlopen打开一个 https 链接时,会验证一次 SSL 证书。
而当目标网站使用的是自签名的证书时就会抛出一个 urllib2.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)> 的错误消息,详细信息可以在这里查看(https://www.python.org/dev/peps/pep-0476/)。

解决方案包括下列两种方式:

1. 使用ssl创建未经验证的上下文,在urlopen中传入上下文参数

  1. import ssl
  2. import urllib2
  3. context = ssl._create_unverified_context()
  4.   print urllib2.urlopen("https://www.12306.cn/mormhweb/", context=context).read()

2. 全局取消证书验证

  1. import ssl 
  2. import urllib2
  3.  ssl._create_default_https_context = ssl._create_unverified_context
  4.   print urllib2.urlopen("https://www.12306.cn/mormhweb/").read()

原文链接如下:

https://blog.csdn.net/moonhillcity/article/details/52767999

猜你喜欢

转载自www.cnblogs.com/lksky/p/9243969.html
今日推荐