解決python打開https出現certificate verify failed的問題
今天遇到一個奇怪的問題,在用urllib打開一個https鏈接的時候,出現了一下報錯信息:IOError: [Errno socket error] [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:727),報錯問題就是證書驗證失敗,這種情況出現在網站使用的是自簽名證書或系統根證書存在問題的時候。
原因:
Python 從 2.7.9版本開始,就默認開啟了服務器證書驗證功能,如果證書校驗不通過,則拒絕后續操作;這樣可以防止中間人攻擊,并使客戶端確保服務器確實是它聲稱的身份。如果是自簽名證書,由于一般系統的CA證書中不存在在自簽名的CA證書內容,從而導致證書驗證不通過。
臨時解決方案
方案1:通過環境部變量設置,關閉服務器證書驗證功能
執行以下shell命令(假設你使用的是bash shell):
echo 'export PYTHONHTTPSVERIFY=0' >> ~/.bashrc
source ~/.bashrc
方案2:取消服務器證書驗證功能(全局影響)
在文件開始部分,加入如下代碼:
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
方案3:創建取消服務器證書驗證的context參數(當前請求代碼影響)
使用示例如下:
import sslcontext = ssl._create_unverified_context()urllib.urlopen(’https://www.baidu.com’, context=context)
方案4:requests verify 參數設置為False,取消驗證功能
使用示例如下:
requests.get(url, verify=False)
方案5:手動指定CA證書(Python3)
使用示例如下:
import urllib
urllib.request.urlopen('https://example.com/some/info', cafile='ca.pem')
當系統根證書存在問題的時候,可以使用 certifi提供的CA證書:
import certifiimport urlliburllib.request.urlopen(’https://example.com/bar/baz.html’, cafile=certifi.where())
補充知識:Python3之關閉SSL證書驗證
報錯信息:
Traceback (most recent call last):File 'D:Python36libsite-packagesurllib3contribpyopenssl.py', line 441, in wrap_socketcnx.do_handshake()File 'D:Python36libsite-packagesOpenSSLSSL.py', line 1806, in do_handshakeself._raise_ssl_error(self._ssl, result)File 'D:Python36libsite-packagesOpenSSLSSL.py', line 1546, in _raise_ssl_error_raise_current_error()File 'D:Python36libsite-packagesOpenSSL_util.py', line 54, in exception_from_error_queueraise exception_type(errors)OpenSSL.SSL.Error: [(’SSL routines’, ’tls_process_server_certificate’, ’certificate verify failed’)]
During handling of the above exception, another exception occurred:
https://aweme.snssdk.com/aweme/v1/play/?video_id=v0200f180000bc4e71kd1dr48pievrrg&line=0&app_id=24
因為網址使用了https,所以經過代理時會報錯;
解決方案:
#參數:verify=Falsehtml = requests.get(item_url, headers=headers, verify=False)# print(html.content)
以上這篇解決python打開https出現certificate verify failed的問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: