# -*- coding: utf-8 -*-
# @Time : 2023/8/4 11:22
# @Author : wangyafeng
# @FileName: 证书过期.py
# @Email : [email protected]
# @Software: PyCharm
import ssl
import socket
import time
from datetime import datetime
def ssl_connect(domain, ip):
# 设置socket的超时时间为5秒
socket.setdefaulttimeout(5)
# 创建默认的SSL上下文
context = ssl.create_default_context()
# 创建一个SSL套接字
skt = context.wrap_socket(socket.socket(), server_hostname=domain)
try:
# 建立SSL连接
skt.connect((ip, 443))
# 获取证书过期时间
end_date = skt.getpeercert()['notAfter'].strip(' GMT')
# 创建一个字典,存储本次连接中的域名、IP 地址和证书过期时间信息
skt_info = {'domain': domain, 'ip': ip, 'end_date': end_date}
except ssl.CertificateError as e:
cert = e
except socket.timeout:
cert = 'Connect refused'
except ConnectionResetError as e:
cert = 'Connect reset' + str(e)
except socket.gaierror as e:
cert = 'Connnect gaierror'
finally:
# 关闭SSL套接字
skt.close()
return skt_info
def check_cert_time(info):
# 获取当前时间戳
current_timestamp = int(time.time())
# 将证书过期时间转换成时间戳
date_object = datetime.strptime(info['end_date'], "%b %d %H:%M:%S %Y")
end_timestamp = int(date_object.timestamp())
# 计算剩余天数
remain_day = (end_timestamp - current_timestamp) / 86400
# 打印域名、IP 地址和证书过期时间信息
print(f"域名:{info['domain']},ip 地址:{info['ip']},证书过期时间:{info['end_date']}")
# 根据剩余天数进行不同的提示
# 如果证书过期时间减去当前时间的天数小于七天的话,则提示需要准备更换证书了
if 0 < remain_day < 7:
print('剩余时间小于七天!请及时更换证书!')
elif remain_day < 0:
print('证书已过期!请及时更换证书!')
else:
print(f"剩余天数为:{remain_day:.2f}天\n")
if __name__ == "__main__":
domains = {}
with open('www.txt', 'r', encoding='utf-8') as file:
for line in file:
domain, ip_pool = line.strip().split(':')
domains[domain] = ip_pool.split(',')
info = [ssl_connect(domain, ip) for domain, ip_pool in domains.items() for ip in ip_pool]
[check_cert_time(i) for i in info]
www.txt
www.baidu.com:180.101.50.242,180.101.50.188
www.bing.com:202.89.233.101,202.89.233.100
www.taobao.com:58.49.198.196
标签:info,domain,socket,证书,ip,ssl,天数
From: https://www.cnblogs.com/wangyafeng/p/17610607.html