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())
相關文章
相關標籤/搜索