使用python 解析SSL证书的域名和过期时间

疑难杂症  

通过ssl模块解析

import ssl

# SSL证书文件路径
cert_file = '/path/to/certificate.pem'

# 解析SSL证书
cert = ssl.load_certificate(ssl.PEM, open(cert_file).read())

# 获取证书的域名
domain = cert.get_subject().commonName  
print("域名:", domain)

# 获取证书的过期时间
expiry_date = cert.get_notAfter()  
print("过期时间:", expiry_date)

通过cryptography解析

from cryptography import x509  
from cryptography.hazmat.backends import default_backend

# SSL certificate file path
cert_file = '/path/to/certificate.pem'

# Load the certificate
with open(cert_file, 'rb') as file:  
    cert_data = file.read()
cert = x509.load_pem_x509_certificate(cert_data, default_backend())

# Get the domain name from the certificate
domain = cert.subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME)[0].value  
print("Domain:", domain)

# Get the expiration date of the certificate
expiry_date = cert.not_valid_after  
print("Expiration Date:", expiry_date)