import ssl
import socket
from datetime import datetime, timedelta
def get_ssl_expiration_date(domain, port=443, timeout=5):
try:
# 创建一个 SSL 上下文
context = ssl.create_default_context()
# 创建一个套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout) # 设置超时时间(秒)
# 连接到指定的域名和端口
sock.connect((domain, port))
# 将普通套接字包装成 SSL 套接字
with context.wrap_socket(sock, server_hostname=domain) as ssock:
# 获取 SSL 证书
cert = ssock.getpeercert()
# 提取证书的到期时间
not_after = cert['notAfter']
expiration_date = datetime.strptime(not_after, '%b %d %H:%M:%S %Y %Z')
return expiration_date
except socket.timeout:
print(f"{domain} 请求超时 999")
# print(f"Connection to {domain} timed out after {timeout} seconds.")
except Exception as e:
print(f"{domain} 请求错误 999")
# print(f"Error fetching SSL certificate for {domain}: {e}")
finally:
sock.close() # 确保套接字被关闭
return None
def main():
# 读取域名列表
with open('domains.txt', 'r') as file:
domains = [line.strip() for line in file]
# 获取当前日期
now = datetime.now()
# 遍历域名列表并获取 SSL 证书到期时间和剩余天数
results = {}
print('域名 过期日期 剩余时间')
for domain in domains:
expiration_date = get_ssl_expiration_date(domain, timeout=1)
if expiration_date:
days_remaining = (expiration_date - now).days
results[domain] = (expiration_date, days_remaining)
print(f"{domain} {expiration_date.strftime('%Y-%m-%d')} {days_remaining}")
# 输出结果
if __name__ == "__main__":
main()
在domains.txt里面写入需要检测的域名,执行脚本进行检测:
赏
使用支付宝打赏
使用微信打赏
若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏