计算网站SSL证书距离当前还有多少天过期
import socket import ssl import datetime import time def get_domain_cert(domain): socket.setdefaulttimeout(5) cxt = ssl.create_default_context() skt = cxt.wrap_socket(socket.socket(),server_hostname=domain) skt.connect((domain,443)) cert = skt.getpeercert() # 获取证书结束的GMT时间 end_time = cert["notAfter"] # 关闭socket连接GMT时间转换 skt.close() # 返回证书过期时间,GMT时间 return end_time def get_end_time(end_time): # 将证书到期时间转换常规可读的时间,还是GMT时间 GMT_FORMAT = '%b %d %H:%M:%S %Y GMT' GMT_TIME = datetime.datetime.strptime(end_time, GMT_FORMAT) # 将证书到期转换成东 8 区的时间 East_8th_District = GMT_TIME + datetime.timedelta(hours=8) print("证书到期时间:%s" %East_8th_District) # 将结束时间转换成时间戳,预备以后做计算,小于多少天报警。 end_time_stamp = time.mktime(East_8th_District.timetuple()) now_time_stamp = time.time() # 算出证书过期的天数 time_difference = end_time_stamp - now_time_stamp # 将时间戳转换成天数 days = ("%.2f" % (time_difference / 60 / 60 / 24)) return days if __name__ == '__main__': END_TIME = get_domain_cert("www.cnblogs.com") days = get_end_time(END_TIME) print("证书过期离当前时间还有:%s 天。" % days)
结果:
标签:end,socket,证书,过期,SSL,时间,time,python3,GMT From: https://www.cnblogs.com/dgshubo/p/16870864.html