Python经过OpenSSL获取指定域名对应的SSL证书

同一台服务器上配置了不一样的虚拟主机域名证书也能够获取到,直接上代码了:python

def get_certificate(hostname, port):
    import idna
    from socket import socket
    from OpenSSL import SSL

    sock = socket()

    sock.connect((hostname, port), )
    ctx = SSL.Context(SSL.SSLv23_METHOD)
    ctx.check_hostname = False
    ctx.verify_mode = SSL.VERIFY_NONE

    sock_ssl = SSL.Connection(ctx, sock)
    sock_ssl.set_tlsext_host_name(idna.encode(hostname))  # 关键: 对应不一样域名的证书
    sock_ssl.set_connect_state()
    sock_ssl.do_handshake()
    cert = sock_ssl.get_peer_certificate()
    sock_ssl.close()
    sock.close()
    return cert


for u in ['https://www.baidu.com/', 'https://mp.weixin.qq.com/', 'https://www.qq.com/']:
    from urllib import parse

    rs = parse.urlparse(u)
    cert = get_certificate(rs.hostname, int(rs.port or 443))
    print(u)
    print('\ttime:', cert.get_notBefore(), '~', cert.get_notAfter())

Last updated