gpt4 book ai didi

python - 禁用 SSL 证书检查 Twisted Agents

转载 作者:太空宇宙 更新时间:2023-11-03 14:09:45 26 4
gpt4 key购买 nike

我正在使用 Twisted (16.3) 和 Treq (15.1) 在 Python (2.7) 中发出异步请求。

我在处理一些通过 HTTPS 的请求时遇到问题。

有些站点的证书无效,因此在向它们发出请求时,我得到以下信息:

twisted.python.failure.Failure OpenSSL.SSL.Error

我希望我的客户信任任何服务器,包括那些没有证书或有自签名证书的服务器。

如何在我的客户端上禁用证书检查?

这是一个与我的基本相同的问题:https://stackoverflow.com/questions/34357439/ssl-options-for-twisted-agents

谢谢!

最佳答案

2019 年 2 月 7 日更新

这是为 treq

创建域白名单的简单方法
from treq.client import HTTPClient
from twisted.web.iweb import IPolicyForHTTPS
from twisted.web.client import BrowserLikePolicyForHTTPS, Agent
from twisted.internet.ssl import CertificateOptions
from twisted.internet import task, defer, ssl
from zope.interface import implementer

@implementer(IPolicyForHTTPS)
class WhitelistContextFactory(object):
def __init__(self, good_domains=None):
"""
:param good_domains: List of domains. The URLs must be in bytes
"""
if not good_domains:
self.good_domains = []
else:
self.good_domains = good_domains

# by default, handle requests like a browser would
self.default_policy = BrowserLikePolicyForHTTPS()

def creatorForNetloc(self, hostname, port):
# check if the hostname is in the the whitelist, otherwise return the default policy
if hostname in self.good_domains:
return ssl.CertificateOptions(verify=False)
return self.default_policy.creatorForNetloc(hostname, port)

@task.react
@defer.inlineCallbacks
def main(reactor):
# make a custom client, agent, and context factory
# NOTE: WhitelistContextFactory() takes a list of BYTES
treq = HTTPClient(Agent(reactor, contextFactory=WhitelistContextFactory([b'example.net'])))
response = yield treq.get('https://example.net/version')
content = yield response.content()
print(content)

WhitelistContextFactory 获取 URL 的 list(以 bytes 为单位)并检查 hostname 是否在列表中忽略 TLS 验证。您也可以花哨并使用正则表达式。感谢https://github.com/twisted/treq/issues/213

不要这样做!

在过去的几天里,我也一直在尝试这样做。通过我为规避证书验证所做的所有努力,我本可以轻松地创建一对 key 并继续我的快乐之路:D。我找到了 this commenttreq 问题板上猴子修补问题:

from twisted.internet import _sslverify
_sslverify.platformTrust = lambda : None

我确信有一种复杂的方法可以“正确”地做到这一点,但我认为不值得付出努力。我做了一个补丁,这样它就不会覆盖 platformTrust(),我会尝试将它合并,但我不会屏住呼吸。从我看到的一些与信任根、SSL 和证书有关的错误评论的语气来看,我认为它不会被合并。希望这会有所帮助。

关于python - 禁用 SSL 证书检查 Twisted Agents,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39704932/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com