我正在编写 Python 2.7.13 (Win x64) 脚本来验证 SSL 证书,并发出问题警报。但是,我遇到了一个问题,即脚本仅在证书有效时才会返回信息。
如果证书无效,我会收到 CERTIFICATE_VERIFY_FAILED SSL 错误。通常我会在出现错误时简单地使用 try/catch 并提醒证书无效,但这里的问题是我需要证书过期的实际日期。
根据 https://docs.python.org/2/library/ssl.html我尝试使用 conn._https_verify_certificates(enable=False) 来禁用证书验证,但收到属性 _https_verify_certificates 不存在的错误。
到目前为止,这是我的代码。我确定我遗漏了一些明显的东西。 Python 肯定可以在不验证的情况下提取 SSL 证书,对吧?
import socket
import ssl
def ssl_expiry_datetime(hostname):
ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z'
context = ssl.create_default_context()
conn = context.wrap_socket(
socket.socket(socket.AF_INET),
server_hostname=hostname,
)
# 3 second timeout because Lambda has runtime limitations
conn.settimeout(3.0)
#conn._https_verify_certificates(enable=False)
conn.connect((hostname, 443))
ssl_info = conn.getpeercert()
# parse the string from the certificate into a Python datetime object
return ['notAfter']
myhost = 'www.google.com'
print ssl_expiry_datetime(myhost)
非常感谢!!!
最佳答案
经过大量试验和错误后,我发现您可以使用 check_hostname 关闭 SSLcertificate 主机名验证。特征。
context.check_hostname = False
如果目标与 SSL 证书上的通用名称 (CN) 不匹配,这将允许您的程序连接到 Web 服务器。但是,当 Web 服务器使用无效的 SSL 证书时,连接将失败并抛出 ConnetionError 错误。 如果目标是获取所有 SSL 证书,即使是无效证书,以下解决方案也只能部分满足您的需求。
这是一个建议的解决方案:
import socket, ssl
def ssl_expiry_datetime(hostname):
ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z'
context = ssl.create_default_context()
context.check_hostname = False
conn = context.wrap_socket(
socket.socket(socket.AF_INET),
server_hostname=hostname,
)
# 3 second timeout because Lambda has runtime limitations
conn.settimeout(3.0)
#conn._https_verify_certificates(enable=False)
conn.connect((hostname, 443))
ssl_info = conn.getpeercert()
# parse the string from the certificate into a Python datetime object
return ['notAfter']
myhost = 'example.com'
print ssl_expiry_datetime(myhost)
或者您可以使用 requests允许您完全关闭验证的库。
引用资料:
- 21.6。 urllib.request — 用于打开 URL 的可扩展库 - https://docs.python.org/3/library/urllib.request.html#urllib.request.urlretrieve
- 17.3.3。 SSL 上下文 - https://docs.python.org/2/library/ssl.html#ssl-contexts
关于python - Python获取无效证书的证书信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43122033/