SSL证书过期巡检脚本

在这里插入图片描述

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()
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值