不记录 'Certificate did not match expected hostname' 错误消息

Don't Log 'Certificate did not match expected hostname' Error Messages

我的网络应用程序请求多个 URL,有时会出现 SSL 证书错误。它们都是第三方 URL,所以我无法修复它们的错误,而且我不想记录它们。然而,有些东西自己记录了这个:2017-08-05 00:22:49,496 ERROR -- : Certificate did not match expected hostname: www.improving-autonomy.org. Certificate: {'subjectAltName': [('DNS', '*.wordpress.com'), ('DNS', 'wordpress.com')], 'subject': ((('commonName', u'*.wordpress.com'),),)} 任何人都知道我怎样才能阻止它?请在下面找到我的代码。非常感谢!

try :
    ua = UserAgent()
    headers = {'Content-Type' : 'text/html', 'Accept-Encoding' : None, 'User-Agent' : ua.random}
    response = requests.get(url, headers=headers, timeout=10)
except ssl.CertificateError as e :
    pass

已更新 -- : 看起来请求模块记录了它 (connection.py)。如果我已经捕捉到相同的异常,为什么它会继续记录?

def _match_hostname(cert, asserted_hostname):
    try:
        match_hostname(cert, asserted_hostname)
    except CertificateError as e:
        log.error(
            'Certificate did not match expected hostname: %s. '
            'Certificate: %s', asserted_hostname, cert
        )
    # Add cert to exception and reraise so client code can inspect
    # the cert when catching the exception, if they want to
    e._peer_cert = cert
    raise

您可以捕获异常然后打印它的类型:

except Exception as exc:
    print exc, exc.message, exc.__class__

然后在您的代码中使用这个特定的异常类型,它应该可以工作。您还可以在 except 语句之后添加一个 else 子句,并将日志记录代码放在那里。仅当 try 块成功执行时才会执行此代码

当然可以。您 捕获了相同的异常,但您没有看到 发生这种情况的地方。让我们来看看这里发生的事情的片段:

except CertificateError as e:
    log.error(
        'Certificate did not match expected hostname: %s. '
        'Certificate: %s', asserted_hostname, cert
    )
# Add cert to exception and reraise so client code can inspect
# the cert when catching the exception, if they want to
e._peer_cert = cert
raise

因此,当第一次引发异常时,该代码捕获 CertificateError,然后生成 log.error,根据代码中的注释将证书分配为属性,然后,调用了 raise

那个空 raise 调用现在将 重新引发 最后一个异常, CertificateError 异常,而 that 就是你要捕获的异常。因此,该代码已经进行了日志调用,并且您的异常捕获是从特定的 raise 调用进行的。