1. 程式人生 > >Python接口自動化--SSL 3

Python接口自動化--SSL 3

ngs pyo 失敗 應該 gpo 校驗 capture isa connect

官方文檔參考地址:

https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings

針對SSL Warnings,urllib3根據不同級別的證書校驗有不同級別的警告,針對這些不同的場景有以下幾種不同的解決辦法

1.不安全的請求警告

  當在沒有啟用證書驗證的情況下對HTTPS URL進行請求時,就會發生這種情況。解決辦法如下:

  參考官方地址:https://urllib3.readthedocs.io/en/latest/user-guide.html#ssl

  urllib3沒有對HTPPS請求做校驗,為了啟用證書驗證,需要安裝一組root證書,最簡單也最現實的實現方法是用certifi包,包含Mozilla的root證書包

  安裝方式:1)、pip install certifi 或者 2)、pip install urllib3[secure]

  安裝好後,當發送請求時,可以通過創建PoolManager進行證書驗證

# _*_ encoding:utf-8 _*_

import requests
import urllib3
import certifi

http = urllib3.PoolManager(
    cert_reqs = CERT_REQUIRED,
    ca_certs = certifi.where()
)
#無異常
http.request(GET,https://www.baidu.com/
) #有異常 http.request(GET,https://expired.badssl.com) #urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host=‘expired.badssl.com‘, port=443): Max retries exceeded with url: / (Caused by SSLError(SSLError(1, u‘[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661)‘),)) #報錯如下 r = requests.get(
https://www.baidu.com/) #requests.exceptions.SSLError: HTTPSConnectionPool(host=‘www.baidu.com‘, port=443): Max retries exceeded with url: / (Caused by SSLError(SSLError(1,
u‘[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661)‘),))

2、不安全的平臺警告

  這種情況發生在具有過時ssl模塊的Python 2平臺上。這些舊的ssl模塊可能會導致一些不安全的請求,從而在它們失敗的地方獲得成功,並在它們應該成功的地方請求失敗。遵循pyOpenSSL指南來解決這個警告。

  官方文檔參考地址:https://urllib3.readthedocs.io/en/latest/user-guide.html#ssl-py2

  pyOpenSSL官方地址:https://pyopenssl.readthedocs.io/en/latest/

3、SNIMissingWarning

  這發生在Python 2版本上,比2.7.9大。這些老版本缺少SNI的支持。這可能導致服務器顯示客戶認為無效的證書。遵循pyOpenSSL指南來解決這個警告。

註:如果在確認該HTTPS請求是安全的,可以訪問時,可以通過以下方法取消警告

import urllib3
urllib3.disable_warnings()
#同時可以通過以下方式抓取日誌
logging.captureWarnings(True)

 

Python接口自動化--SSL 3