ssl新闻资讯

文档中心

Python瀹炴垬3绉嶆柟娉曡交鏉捐幏鍙朣SL璇佷功淇℃伅锛堥檮浠g爜绀轰緥锛?txt

时间 : 2025-09-27 16:31:40浏览量 : 3

2Python瀹炴垬3绉嶆柟娉曡交鏉捐幏鍙朣SL璇佷功淇℃伅锛堥檮浠g爜绀轰緥锛?txt

SSL证书是网络安全的重要基石,它就像网站的"身份证",验证网站的真实性并加密传输数据。作为安全从业者,我经常需要用Python自动化检查SSL证书信息。下面分享3种实用的Python获取SSL证书方法,附带完整代码示例。

方法一:使用ssl标准库(内置模块)

Python自带的ssl模块是最基础的选择:

```python

import ssl

import socket

from datetime import datetime

def get_cert_basic(hostname, port=443):

context = ssl.create_default_context()

with socket.create_connection((hostname, port)) as sock:

with context.wrap_socket(sock, server_hostname=hostname) as ssock:

cert = ssock.getpeercert()

print(f"证书主题: {cert['subject']}")

print(f"签发者: {cert['issuer']}")

expire_date = datetime.strptime(cert['notAfter'], '%b %d %H:%M:%S %Y %Z')

days_left = (expire_date - datetime.now()).days

print(f"剩余有效期: {days_left}天")

示例用法

get_cert_basic("www.baidu.com")

```

输出示例

证书主题: ((('countryName', 'CN'),), (('stateOrProvinceName', 'Beijing'),), (('localityName', 'Beijing'),), (('organizationName', 'Beijing Baidu Netcom Science Technology Co., Ltd'),), (('organizationalUnitName', 'service operation department'),), (('commonName', 'www.baidu.com'),))

签发者: ((('countryName', 'US'),), (('organizationName', 'DigiCert Inc'),), (('organizationalUnitName', 'www.digicert.com'),), (('commonName', 'DigiCert Secure Site Pro CN CA G3'),))

剩余有效期: 287天

适用场景:快速检查证书基本信息和过期时间,适合集成到监控脚本中。

方法二:使用cryptography库(专业级解析)

需要更详细的证书信息时,cryptography库是专业选择:

from cryptography import x509

from cryptography.hazmat.backends import default_backend

def get_cert_details(hostname, port=443):

cert_pem = ssl.get_server_certificate((hostname, port))

cert = x509.load_pem_x509_certificate(cert_pem.encode(), default_backend())

print("=== 扩展信息 ===")

for ext in cert.extensions:

print(f"{ext.oid._name}: {ext.value}")

print("\n=== SAN(主题备用名称) ===")

san_ext = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName)

for name in san_ext.value:

print(name.value)

get_cert_details("github.com")

典型输出

=== 扩展信息 ===

subjectKeyIdentifier:

authorityKeyIdentifier:

basicConstraints:

keyUsage:

extendedKeyUsage: ])>

crlDistributionPoints:

certificatePolicies:

=== SAN(主题备用名称) ===

github.com

www.github.com

优势:可以解析更专业的证书字段,如密钥用法、CRL分发点等安全关键信息。

方法三:使用requests+OpenSSL组合(面向爬虫场景)

在做安全爬虫时,常需要批量验证证书:

import requests

from OpenSSL import SSL, crypto

def verify_cert_chain(url):

try:

response = requests.get(url, timeout=5)

cert_der = response.connection.sock.getpeercert(binary_form=True)

cert = crypto.load_certificate(crypto.FILETYPE_ASN1, cert_der)

验证证书链有效性(模拟浏览器验证过程)

store = crypto.X509Store()

store.set_flags(crypto.X509StoreFlags.PARTIAL_CHAIN)

添加中间CA证书(以Let's Encrypt为例)

ca_cert = """--BEGIN CERTIFICATE--

MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/

...

--END CERTIFICATE--"""

ca_cert = crypto.load_certificate(crypto.FILETYPE_PEM, ca_cert)

store.add_cert(ca_cert)

store_ctx = crypto.X509StoreContext(store, cert)

store_ctx.verify_certificate()

print(f"{url} 证书链验证通过")

return True

except Exception as e:

print(f"{url} 证书异常: {str(e)}")

return False

批量检测示例

sites = ["https://bank.example.com", "https://phishing-site.fake"]

for site in sites:

verify_cert_chain(site)

安全提示:此方法可以检测以下常见问题:

- 自签名证书(缺少CA签名)

- 过期/未生效的证书

- CN与域名不匹配

- 被吊销的证书(需配合CRL或OCSP检查)

SSL检查的5个企业级实践建议

1. 有效期监控:建议在到期前30天触发告警

```python

if days_left < 30:

send_alert(f"紧急:{hostname} SSL证书即将过期")

```

2. 密钥强度检查:拒绝弱密钥算法

```python

if "sha1WithRSAEncryption" in cert.signature_algorithm:

block_access("检测到不安全的SHA1签名算法")

3. OCSP装订验证(实时吊销检查)

import ocspchecker

status = ocspchecker.check(url).ocsp_status

4. HSTS预加载检测

if "strict-transport-security" not in response.headers:

log_warning("缺失HSTS头")

5. 混合内容扫描

if any(url.startswith("http://") for url in page_resources):

report_violation("页面包含非HTTPS资源")

对比表

| 方法 | 优点 | 缺点 | 适用场景 |

||||-|

| ssl模块 | Python内置无需安装 | 信息较基础 | 快速检查/监控脚本 |

| cryptography | RFC标准解析专业 | API较复杂 | CA系统/深度分析 |

| requests+OpenSSL | 支持完整链式验证 | 依赖较多组件 | Web爬虫/企业巡检 |

建议将以上代码封装成自动化工具定期运行,特别是对金融、电商等关键业务系统。我曾用类似方案帮客户发现过即将过期的支付网关证书,避免了重大生产事故。记住:好的安全防护一定是预防大于补救!

TAG:python获取ssl证书,python获取ssl证书信息,python ssl模块详解,python获取https