传统运维 - 获取域名ssl过期时长

2023-03-02
#!/bin/bash

: '
获取证书过期时间
当输出时间为0,则该域名无证书
维护domain_ssl.info-${domain},请从云厂商处下载或者通过api获取,按行分割,域名前缀:${端口},如仅有域名前缀,则端口默认为443
'

# 加载环境变量
. /etc/profile
. ~/.bash_profile
. /etc/bashrc

# 证书过期时间
days="30"
# 脚本所在目录即脚本名称
script_dir=$( cd "$( dirname "$0"  )" && pwd )
script_name=$(basename ${0})

domain='yqn.com'
read -p "请输入顶级域名,如yqn.com:" domain
file_name="domain_ssl.info-"${domain}
if [[ ! -f ${file_name} ]];then
    echo "error"
    exit 1
fi

temp_result_file="/tmp/${domain}"
result_file=${temp_result_file}-result
rm -f ${temp_result_file}
readFile="${script_dir}/${file_name}"
grep -v '^#' ${readFile} | while read line;do #读取存储了需要监测的域名的文件
    # echo "${line}"
    get_domain_prefix=$(echo "${line}" | awk -F ':' '{print $1}')
    get_domain=${get_domain_prefix}.${domain}
    get_port=$(echo "${line}" | awk -F ':' '{print $2}')
    if [[ -z ${get_port} ]];then
        get_port=443
    fi

    # echo ${get_domain}
    # echo "${get_port}"
    # echo "======"
    result=$(nmap ${get_domain} -p ${get_port}| grep open)
    if [[ ${result} =~ "open" ]];then
        END_TIME=$(echo | openssl s_client -servername ${get_domain}  -connect ${get_domain}:${get_port} 2>/dev/null | openssl x509 -noout -dates |grep 'After'| awk -F '=' '{print $2}'| awk -F ' +' '{print $1,$2,$4 }' )
        #使用openssl获取域名的证书情况,然后获取其中的到期时间
        END_TIME1=$(date +%s -d "$END_TIME") #将日期转化为时间戳
        NOW_TIME=$(date +%s -d "$(date | awk -F ' +'  '{print $2,$3,$6}')") #将目前的日期也转化为时间戳

        RST=$(($(($END_TIME1-$NOW_TIME))/(60*60*24))) # 到期时间减去目前时间再转化为天数
        if [[ ${RST} -le ${days} ]];then
            echo ${RST} ${get_domain} "todo" >> ${temp_result_file}
#        else
#            echo ${RST} ${get_domain} >> ${temp_result_file}
        fi
    else
        echo ${get_domain} >> ${temp_result_file}-error
    fi
done
cat ${temp_result_file} | sort -nk1 > ${result_file}
echo "最终结果输出至:"${result_file}

标题:传统运维 - 获取域名ssl过期时长
地址:https://blog.njqhome.com:8443/articles/2022/02/07/1644226900819.html