import socket
import ssl
import datetime
# author 波哥(IT运维技术圈)
# 域名列表
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))