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

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

```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())
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://close.gitbook.io/yun-wei-bi-ji/python/python-xiao-ji-qiao/python-jing-guo-openssl-huo-qu-zhi-ding-yu-ming-dui-ying-de-ssl-zheng-shu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
