首頁  >  文章  >  後端開發  >  如何在 Python 請求中停用 SSL 憑證驗證?

如何在 Python 請求中停用 SSL 憑證驗證?

DDD
DDD原創
2024-10-27 06:04:29392瀏覽

How can I disable SSL certificate verification in Python requests?

在Python 請求中停用安全憑證驗證

發出HTTPS 要求時,Python 的requests 程式庫會驗證伺服器的SSL 憑證以確保連接SSL 憑證以確保連線安全。但是,在某些情況下,例如造訪憑證過期的網站時,您可能想要停用此驗證。

若要停用憑證驗證,請在 requests.post 函數中使用 verify 參數。將其設為 False,如下所示:

<code class="python">import requests
requests.post(url='https://foo.example', data={'bar':'baz'}, verify=False)</code>

這允許在不驗證 SSL 憑證的情況下發出請求。然而,值得注意的是,這可能會帶來安全風險,因為它可能導致中間人攻擊。請謹慎使用此選項。

使用上下文管理器進行SSL 驗證

如果您需要對特定上下文中的多個請求停用SSL 驗證,您可以使用上下文管理器如下:

<code class="python">import warnings
import contextlib

import requests
from urllib3.exceptions import InsecureRequestWarning

old_merge_environment_settings = requests.Session.merge_environment_settings

@contextlib.contextmanager
def no_ssl_verification():
    opened_adapters = set()

    def merge_environment_settings(self, url, proxies, stream, verify, cert):
        # ...

    requests.Session.merge_environment_settings = merge_environment_settings

    try:
        with warnings.catch_warnings():
            warnings.simplefilter('ignore', InsecureRequestWarning)
            yield
    finally:
        requests.Session.merge_environment_settings = old_merge_environment_settings

        for adapter in opened_adapters:
            try:
                adapter.close()
            except:
                pass

with no_ssl_verification():
    # Make requests without SSL verification here</code>

此上下文管理器暫時將區塊內發出的所有請求的verify 設定為False,然後在區塊退出時恢復為預設行為。它還會抑制否則會觸發的 SSL 警告。

以上是如何在 Python 請求中停用 SSL 憑證驗證?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn