场景:自动化SSL/TLS证书的申请、续期和部署,避免证书过期导致服务中断。
示例:使用Shell脚本配合Let's Encrypt的Certbot工具自动续期证书。
#!/bin/bash # 自动续期Let's Encrypt证书并重启服务 certbot renew --quiet --post-hook "systemctl reload nginx"
扩展案例:检查证书过期时间并触发告警。
import ssl import socket import datetime import smtplib def check_cert_expiry(domain, port=443): context = ssl.create_default_context() with socket.create_connection((domain, port)) as sock: with context.wrap_socket(sock, server_hostname=domain) as ssock: cert = ssock.getpeercert() expires_on = datetime.datetime.strptime(cert['notAfter'], '%b %d %H:%M:%S %Y %Z') days_left = (expires_on - datetime.datetime.now()).days return days_left domain = "example.com" threshold = 30 days_left = check_cert_expiry(domain) if days_left < threshold: msg = f"证书 {domain} 将在 {days_left} 天后过期!" smtp_server = smtplib.SMTP('smtp.example.com', 587) smtp_server.login('admin@example.com', 'password') smtp_server.sendmail('admin@example.com', 'ops-team@example.com', msg) smtp_server.quit()