python - Python获取无效证书的证书信息

标签 python python-2.7 ssl

我正在编写 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允许您完全关闭验证的库。

引用资料:

  1. 21.6。 urllib.request — 用于打开 URL 的可扩展库 - https://docs.python.org/3/library/urllib.request.html#urllib.request.urlretrieve
  2. 17.3.3。 SSL 上下文 - https://docs.python.org/2/library/ssl.html#ssl-contexts

关于python - Python获取无效证书的证书信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43122033/

相关文章:

python - 将迭代器链接到平面迭代器

java - Tomcat SSL 证书更新问题 (SSL23_GET_SERVER_HELLO :sslv3 alert handshake failure)

java - Socket getOutputStream 耗时太长

在 tomcat 的 server.xml 配置 SSL 后,Eclipse 无法启动 tomcat 服务器

python导入模块用于另一个py文件中的代码

python - Pandas 发送多个 DataFrames to_csv

python-2.7 - pyglet 将屏幕解析为变量

python - 是否有一个函数可以检查字符串中的字符是否是字母表中的字母? ( swift )

python - 从文本到字典,更新键值

python - 当有很多线程时,队列不会处理所有元素