如何使用 python 获取主题 dn

How to get subject dn with python

使用 python 获取 SSL 的主题 DN 的好方法是什么?

这包括:

类似于:

import ssl
import socket
from pprint import pprint


hostname = 'www.example.com'
context = ssl.create_default_context()

with socket.create_connection((hostname, 443)) as sock:
    with context.wrap_socket(sock, server_hostname=hostname) as ssock:
        pprint(ssock.getpeercert()['subject'])

输出:

((('countryName', 'US'),),
 (('stateOrProvinceName', 'California'),),
 (('localityName', 'Los Angeles'),),
 (('organizationName', 'Internet Corporation for Assigned Names and Numbers'),),
 (('commonName', 'www.example.org'),))

在此处阅读有关 getpeercert() 的更多信息:https://docs.python.org/3/library/ssl.html#ssl.SSLSocket.getpeercert