記一個python requests模塊請求的報錯


今日突然發現線上出了一堆bug, 最終定位在 服務器上, 用python 請求一個 https協議的地址時, 出現了報錯, 而這個報錯阻擋了后續邏輯
報錯內容是這樣的:

SSLError: HTTPSConnectionPool(host='hooks.slack.com', port=443): Max retries exceeded with url: /services/T92******** (Caused by SSLError(SSLError(1, '_ssl.c:510: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure'),))

首先根據 ssl 懷疑是 證書問題;並且經測試, http協議的請求沒有出錯
先用 requests.post(url, verify=False) 關閉證書驗證測試, 沒有用, 還是這個報錯
然后懷疑是庫版本的問題, 用另一台服務器測試, 並沒有出現這個報錯,然后比對 兩台服務器的不同, 相同的地方都暫不修改

  1. requests 庫的版本 ,都是最新的 2.23.0
  2. 本地 openssl 的版本: openssl version , 都是 OpenSSL 1.0.1f 6 Jan 2014; 這個版本確實應該升級, 但是這個庫比較底層, 不敢隨便升級,而且升級起來也是比較麻煩的(在自用的服務器上搞過); 鑒於兩台服務器上版本都一樣, 也放棄了從這修改
  3. 本地ubuntu版本, https://stackoverflow.com/a/31678467/11697500 這個回答中提到 把系統版本升級到 14.10 解決了這個問題,但是鑒於和openssl 相同的考慮, 比較兩台服務器 系統版本
    可以用 lsb-release 查看系統版本, 我兩台服務器都是 一樣的,Ubuntu 14.04.5 LTS

求助谷歌, 和這個問題描述的基本一致:

https://stackoverflow.com/questions/31649390/python-requests-ssl-handshake-failure?answertab=votes#tab-top

這里有人建議 使用 pip install requests[security] 安裝 requests庫, 關於 和 直接 pip install requests 的區別, [這里][https://stackoverflow.com/a/31812342/11697500] 有解釋,我摘抄一下

  • 使用pip install requests[security], 會額外安裝 三個庫, 分別是:pyOpenSSL , cryptography , idna

於是 用 pip install requests[security] 重新安裝 requests庫
遇到了這個問題:

pyopenssl 19.1.0 has requirement cryptography>=2.8, but you'll have cryptography 1.9 which is incompatible.
```
那就是 pyopenssl 和 cryptography 都沒有安裝成功,先更新 cryptography 這個庫:
```
pip install --upgrade cryptography

From cffi callback <function _verify_callback at 0x7ffa9dc05668>:
Traceback (most recent call last):
  File "/mnt/slots_spin/lib/slots_admin/venv/local/lib/python2.7/site-packages/OpenSSL/SSL.py", line 314, in wrapper
    _lib.X509_up_ref(x509)
AttributeError: 'module' object has no attribute 'X509_up_ref'
Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError("bad handshake: Error([('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE', 'certificate verify failed')],)",),)': /simple/cryptography/
```
最后一行報錯比較眼熟, 和我們最初的問題一樣, 發現 pip 的操作也會報這個錯
試着 搜`AttributeError: 'module' object has no attribute 'X509_up_ref'`,  無果
又直接搜 `更新 cryptography`, 找到一個非常切合的帖子:  `https://github.com/erjosito/ansible-azure-lab/issues/5#issuecomment-387747004`
這個問題中, 答主建議 先卸載 pyopenssl 和 cryptography, 再重新安裝
```
pip uninstall pyOpenSSL cryptography
sudo pip install pyOpenSSL cryptography
```
成功,估計這兩個庫的版本不匹配, 所以前面安裝失敗
然后 重新執行 `pip install requests[security]`

成功,https請求也能正常執行了

雖然問題解決了 , 但是為什么突然會出問題, 還是有些疑問


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM