我正在编写一个 Python 2.7.13 (Win x64) 脚本来验证 SSL 证书并发出问题警报。但是,我遇到了一个问题,即仅当证书有效时脚本才会返回信息。
如果证书无效,我会收到 CERTIFICATE_VERIFY_FAILED SSL 错误。通常,当出现错误时,我会简单地使用 try/catch 并警告证书无效,但这里的问题是我需要证书过期的实际日期。
Per 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)
非常感谢!!!!
经过大量试验和错误后,我发现您可以使用以下命令关闭 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)