最近在玩一些開源項(xiàng)目的時(shí)候,編譯腳本需要使用urllib2去一些https網(wǎng)站去拉取一些東西法精,結(jié)果遇到以下問(wèn)題:
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 429, in open
response = self._open(req, data)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 447, in _open
'_open', req)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 407, in _call_chain
result = func(*args)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1241, in https_open
context=self._context)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1198, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)>
因?yàn)楸镜貦C(jī)器安裝有anaconda的python3和默認(rèn)的python2徒河,而系統(tǒng)默認(rèn)的python是3.x版本的系馆。開始的時(shí)候走了彎路,一直懷疑是著python3中的openssl版本不對(duì)虚青,嘗試修改用處不大它呀。再后來(lái)結(jié)合代碼和日志看出來(lái)這個(gè)是python2的問(wèn)題。
再進(jìn)行搜索發(fā)現(xiàn)這個(gè)問(wèn)題是從python2.7.9開始引入的棒厘,是為了防止中間人攻擊纵穿,在訪問(wèn)https的時(shí)候會(huì)檢查服務(wù)器證書簽名是否是CA的可信任根證書。報(bào)錯(cuò)就是發(fā)生在這個(gè)過(guò)程奢人。
解決方法有兩種:
- 比較快但是不太安全的方法
export PYTHONHTTPSVERIFY=0
python your_script
或者PYTHONHTTPSVERIFY=0 python your_script
- 在自己腳本中加入處理:
import os, ssl
if (not os.environ.get('PYTHONHTTPSVERIFY', '') and
getattr(ssl, '_create_unverified_context', None)):
ssl._create_default_https_context = ssl._create_unverified_context
參考:
http://www.reibang.com/p/d3b60e42fc02
https://moreless.medium.com/how-to-fix-python-ssl-certificate-verify-failed-97772d9dd14c