Shell版
demo.txt
[root@bogon aihuidi]# cat demo.txt
www.aihuidi.com:111.222.333.444
xxx.xxx.com:ip,ip
脚本:
[root@localhost aihuidi]# vim check_ssl.sh
#!/bin/bash
for line in $(cat demo.txt)
do
domain=$(echo ${line} | awk -F ':' '{print $1}')
ip_pool=$(echo ${line} | awk -F '[a-z]:' '{print $2}'| sed 's/\,/ /g')
#遍历IP池
for ip in ${ip_pool}
do
echo -e "\e[33m----------------start to check----------------\e[0m"
echo -e "ip: ${ip}\ndomain: ${domain}"
text=$(echo | openssl s_client -servername ${domain} -connect ${ip}:443 2>/dev/null | openssl x509 -noout -dates )
if [[ ${text} ]]
then
#证书过期时间
end_date=$(echo "$text" | grep -i "notAfter" | awk -F '=' '{print $2}')
#转换时间戳
end_timestamp=$(date -d "$end_date" +%s)
#当前时间戳
current_temestamp=$(date +%s)
#计算证书到期剩余天数
remain_date=$(( (${end_timestamp} - ${current_temestamp}) / 86400 ))
# 如果证书过期时间减去当前时间的天数小于七天的话,则提示需要准备更换证书了
if [[ ${remain_date} -lt 7 && ${remain_date} -ge 0 ]]
then
echo -e "\e[31m剩余时间小于七天!请及时更换证书!\e[0m"
echo -e "\e[31mip: ${ip}, ${domain}\e[0m"
elif [[ ${remain_date} -lt 0 ]]
then
echo -e "\e[31m证书已过期!请及时更换证书!\e[0m"
else
echo -e "\e[32m剩余天数为:${remain_date}\e[0m"
fi
else
echo -e "\e[31mError!${ip}\e[0m"
echo -e "\e[31m${domain}\e[0m"
fi
done
done
#运行脚本
[root@localhost aihuidi]# ./check_ssl.sh
参数解释
其中 notBefore 是开始时间,notAfter 是过期时间
Python版
import socket
import ssl
import datetime
def get_certificate_expiry_date(domain):
try:
context = ssl.create_default_context()
with socket.create_connection((domain, 443)) as sock:
with context.wrap_socket(sock, server_hostname=domain) as ssock:
cert = ssock.getpeercert()
expiry_date_str = cert['notAfter']
expiry_date = datetime.datetime.strptime(expiry_date_str, '%b %d %H:%M:%S %Y %Z')
return expiry_date
except Exception as e:
print("Error:", e)
return None
def main():
domain = "aihuidi.blog.csdn.net" # 替换为你要检测的域名
expiry_date = get_certificate_expiry_date(domain)
if expiry_date:
current_date = datetime.datetime.now()
days_left = (expiry_date - current_date).days
print(f"SSL证书到期时间:{expiry_date}")
print(f"剩余天数:{days_left} 天")
if __name__ == "__main__":
main()