+
50
-

python如何查看ssl数字证书是否过期,还剩多少天过期?

python如何查看ssl数字证书是否过期,还剩多少天过期?


网友回复

+
0
-

可以直接给他一个开通了ssl证书的网站域名,就能算出ssl证书是否过期,还剩多少天,适合ssl证书远程监控报警,代码如下:

import ssl
import socket
from datetime import datetime

def check_ssl_expiry(hostname, port=443):
    ssl_context = ssl.create_default_context()
    conn = ssl_context.wrap_socket(socket.socket(socket.AF_INET), server_hostname=hostname)
    
    # 3秒应该足以建立连接
    conn.settimeout(3.0)
    
    try:
        conn.connect((hostname, port))
        ssl_info = conn.getpeercert()
    except Exception as e:
        print(f"Error: {e}")
        return None
    finally:
        conn.close()
        
    # 获取证书的过期时间
    expire_date = datetime.strptime(ssl_info['notAfter'], '%b %d %H:%M:%S %Y %Z')
    # 当前时间
    current_date = datetime.utcnow()
    # 打印剩余天数
    days_remaining = (expire_date - current_date).days
    
    return days_remaining

# 测试函数,查看www.example.com的证书有效期
days_left = check_ssl_expiry('www.bfw.wiki')
if days_left is not None:
    if days_left > 0:
        print(f"The SSL certificate will expire in {days_left} days.")
    else:
        print("The SSL certificate has expired or is about to expire.")

我知道答案,我要回答