脚本说明:
批量查询域名证书过期时间的脚本,这个需求应该是比较普遍的。DOMAIN_LIST用来填写域名列表,其他没什么需要特别说明的,这个是个python3的脚本脚本功能:
需要特别说明的是距离过期还剩这个是按照当前时间来计算,还剩多少天过期。
import socket
import ssl
import datetime
# author blog.ossq.cn
# 域名列表
DOMAIN_LIST = [
"www.98dev.com",
"www.baidu.com",
"www.yahoo.com",
"www.microsoft.com"
]
# 解析IP地址
def resolve_domain(domain):
try:
ips = socket.getaddrinfo(domain, None)
return \[ip\[4\]\[0\] for ip in ips\]
except:
return \[\]
# 获取证书信息
def get_certificate_info(domain):
context = ssl.create_default_context()
with socket.create_connection((domain, 443)) as sock:
with context.wrap_socket(sock, server_hostname=domain) as sslsock:
cert = sslsock.getpeercert()
subject = dict(x\[0\] for x in cert\['subject'\])
issued_to = subject.get('commonName')
issuer = dict(x\[0\] for x in cert\['issuer'\])
issued_by = issuer.get('organizationName')
valid_from = datetime.datetime.strptime(cert\['notBefore'\], '%b %d %H:%M:%S %Y %Z')
valid_to = datetime.datetime.strptime(cert\['notAfter'\], '%b %d %H:%M:%S %Y %Z')
expire_days = (valid_to - datetime.datetime.utcnow()).days
return (issued_to, valid_from, valid_to, expire_days, issued_by)
# 打印结果
def print_result(domain, info):
print("="\*50)
print("Domain: {0}".format(domain))
print("通用名: {0}".format(info\[0\]))
print("生效日期: {0}".format(info\[1\]))
print("到期日期: {0}".format(info\[2\]))
print("距离过期还剩: {0} 天".format(info\[3\]))
print("颁发机构: {0}".format(info\[4\]))
ips = resolve_domain(domain)
if ips:
print("解析地址: {0}".format(", ".join(ips)))
else:
print("解析地址: N/A")
print("="\*50)
`# 主程序
if `name` == "`main`":
for domain in DOMAIN_LIST:
try:
info = get_certificate_info(domain)
print_result(domain, info)
except:
print("无法获取域名 {0} 的证书信息".format(domain))`
执行效果如下: