在python中使用urllib2庫(kù)去訪問(wèn)一個(gè)自簽名的網(wǎng)站時(shí)诞仓,會(huì)出現(xiàn)如下報(bào)錯(cuò):
urllib2.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)>
出現(xiàn)以上錯(cuò)誤的原因是因?yàn)閜ython的版本問(wèn)題挤聘,在python2.6(含2.6)以下版本中蚂踊,在訪問(wèn)HTTPS的網(wǎng)站時(shí)霸旗,TLS握手期間不會(huì)檢查服務(wù)器X509的證書(shū)簽名是否是CA的可信任根證書(shū)颂跨。這種局面在python2.7 3.4 和 3.5版本中得到了修改似炎。
所以关贵,以下代碼在python2.6版本中測(cè)試是完全沒(méi)有問(wèn)題的
import json
import urllib
import urllib2
url='https://www.20150509.cn:1559'
def test():
pre_data = [{"client":"local", "tgt":"*", "fun":"test.ping"}]
json_data = json.dumps(pre_data)
header = {"Content-Type":"application/json", "Accept":"application/json", "X-Auth-Token":"b91e7uj86g4f97cc**********b92778ujh4kedf"}
request = urllib2.Request(url, json_data, header)
response = urllib2.urlopen(request)
html = response.read()
print html
if __name__=="__main__":
test()
運(yùn)行測(cè)試
shell> python sa.py
{"return": [{"vm3.salt.com": true, "vm2.salt.com": true, "ph1.salt.com": true, "ph2.salt.com": true, "vm1.salt.com": true, "vm4.salt.com": true, "localhost": true, "vm7.salt.com": true}]}
在python2.7+版本就會(huì)報(bào)上述錯(cuò)誤
shell> python sa.py
Traceback (most recent call last):
File "sa.py", line 25, in <module>
test()
File "sa.py", line 17, in test
response = urllib2.urlopen(request)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 431, in open
response = self._open(req, data)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 449, in _open
'_open', req)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 409, in _call_chain
result = func(*args)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1240, in https_open
context=self._context)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1197, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)>
解決方法:
import json
import urllib
import urllib2
import ssl #add line 1
ssl._create_default_https_context = ssl._create_unverified_context #add line 2
url='https://www.20150509.cn:1559'
def test():
pre_data = [{"client":"local", "tgt":"*", "fun":"test.ping"}]
json_data = json.dumps(pre_data)
header = {"Content-Type":"application/json", "Accept":"application/json", "X-Auth-Token":"b91e7uj86g4f97cc**********b92778ujh4kedf"}
request = urllib2.Request(url, json_data, header)
response = urllib2.urlopen(request)
html = response.read()
print html
if __name__=="__main__":
test()