備忘錄_20160105(定位)
修改
回首頁
程式 2026-02-05 11:21:01 1770261661 100
python 查詢網站 ssl 的憑證到期日
python 查詢網站 ssl 的憑證到期日
import ssl
import socket
from datetime import datetime
def get_ssl_expiry_date(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()
# 取得過期日期並轉為 datetime 格式
expiry_str = cert['notAfter']
expiry_date = datetime.strptime(expiry_str, '%b %d %H:%M:%S %Y %Z')
return expiry_date
# 測試
hostname = 'tw.yahoo.com'
expiry_date = get_ssl_expiry_date(hostname)
print(f"{hostname} 的 SSL 憑證到期日是:{expiry_date}")