ssl新闻资讯

文档中心

Python瀹炴垬3绉嶆柟娉曞揩閫熸煡鎵維SL璇佷功淇℃伅锛堥檮浠g爜绀轰緥锛?txt

时间 : 2025-09-27 16:30:29浏览量 : 3

SSL证书的重要性

2Python瀹炴垬3绉嶆柟娉曞揩閫熸煡鎵維SL璇佷功淇℃伅锛堥檮浠g爜绀轰緥锛?txt

想象一下SSL证书就像是网站的"身份证"和"加密锁"。当你在浏览器地址栏看到那个小锁图标时,就说明这个网站使用了SSL证书,你的通信是加密的。作为网络安全人员,我们经常需要检查这些证书的有效性、颁发者和过期时间等信息。

举个例子:去年某大型电商平台因为SSL证书过期未续费,导致整个网站无法访问2小时,直接损失上百万。如果我们能用Python自动监控证书状态,这种事故完全可以避免!

Python查看SSL证书的3种方法

方法1:使用ssl标准库(最基础)

Python自带的ssl模块就像瑞士军刀的基础工具,能满足大多数日常需求:

```python

import ssl

import socket

from datetime import datetime

def get_cert_info(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']}")

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_info("www.baidu.com")

```

这个方法会输出类似:

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

剩余有效期: 89天

方法2:使用cryptography库(专业级)

如果需要更专业的解析,cryptography库就像网络安全专家的专业工具箱:

from cryptography import x509

from cryptography.hazmat.backends import default_backend

def get_cert_details(hostname):

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

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

print("颁发者:", cert.issuer.rfc4514_string())

print("使用者:", cert.subject.rfc4514_string())

print("有效期:", cert.not_valid_after)

检查是否过期

from datetime import datetime

if cert.not_valid_after < datetime.now():

print("?? 警告:证书已过期!")

get_cert_details("github.com")

输出示例:

颁发者: CN=DigiCert TLS Hybrid ECC SHA384 2025 CA1, O="DigiCert, Inc.", C=US

使用者: CN=github.com, O="GitHub, Inc.", L=San Francisco, ST=California, C=US

有效期: 2025-03-15 23:59:59

方法3:使用requests+OpenSSL组合(高级技巧)

这就像把狙击枪和望远镜组合使用,适合需要深度检查的场景:

import requests

from OpenSSL import crypto

def ***yze_cert_chain(url):

resp = requests.get(url)

cert_der = resp.raw.connection.sock.getpeercert(binary_form=True)

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

提取关键信息

subject = dict(item[0] for item in cert.get_subject().get_components())

print(f"通用名称(CN): {subject[b'CN'].decode()}")

***yze_cert_chain("https://weibo.com")

SSL检查实战案例

案例1:批量检查域名证书状态

假设你需要管理100个域名的SSL状态:

import concurrent.futures

domains = ["baidu.com", "taobao.com", "jd.com", "qq.com"]

def check_domain(domain):

try:

get_cert_info(domain)

return f"{domain}: ?正常"

except Exception as e:

return f"{domain}: ?异常({str(e)})"

with concurrent.futures.ThreadPoolExecutor() as executor:

results = executor.map(check_domain, domains)

for result in results:

print(result)

案例2:监控即将过期的证书

def monitor_expiry(domain, warning_days=30):

_, expire_date = get_cert_info(domain)

if (expire_date - datetime.now()).days < warning_days:

send_alert_email(f"{domain} SSL将在{(expire_date - datetime.now()).days}天后过期!")

monitor_expiry("yourcompany.com")

SSL安全小贴士

1. 常见问题排查

- ERR_CERT_DATE_INVALID → 检查服务器时间是否正确

- ERR_CERT_AUTHORITY_INVALID → CA根证书可能不被信任

2. 安全建议

- TLS版本至少使用1.2(禁用SSLv3)

- 定期轮换密钥(建议每年一次)

- OCSP装订配置可以减少验证延迟

3. 免费工具推荐

- SSL Labs测试(https://www.ssllabs.com/ssltest/)

- crt.sh → CA签发的所有证书查询平台

与进阶学习

通过Python自动化SSL检查就像给网站安排了一个24小时值班的安全卫士。掌握了这些技能后,你可以进一步:

1. 开发Flask/Django插件实时监控内网所有服务

2. 结合Zabbix/Prometheus做可视化监控大盘

3. 编写浏览器插件提醒用户访问的站点证书状态

记住一个原则:在网络安全领域,"信任但要验证"(Trust but verify)。即使是最可靠的CA颁发的证书也需要定期检查!

TAG:python查找ssl证书信息,python爬虫ssl错误,python3 ssl,python中ssl模块,python ssl certificate,python获取ssl证书信息