Bash 脚本用于计算网站 SSL 证书剩余到期天数

Bash 脚本用于计算网站 SSL 证书剩余到期天数

我有一个名为的网站xplosa.com,它有一个有效的 SSL 证书,我通过 bash 脚本应该能够计算剩余的到期天数。我知道有很多替代方法可以完成这项工作,但我喜欢使用 Ubuntu bash。顺便说一句,我正在使用Ubuntu 18.04

这是我的示例逻辑

#!/bin/bash

get_the_cert_expiry_date() {
    # command to retrieve the expiry date
}

currentDate="$(date +%Y-%m-%d)"
website="xplosa.com"
certExpDate="$(get_the_cert_expiry_date)"
count=$((currentDate - certExpDate))

echo "remaining days for expiry: ${count}"
  • 这是正确的逻辑吗?
  • 如何实现get_the_cert_expiry_date

答案1

这应该有效

#!/bin/bash

website="xplosa.com"
certificate_file=$(mktemp)
echo -n | openssl s_client -servername "$website" -connect "$website":443 2>/dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > $certificate_file
date=$(openssl x509 -in $certificate_file -enddate -noout | sed "s/.*=\(.*\)/\1/")
date_s=$(date -d "${date}" +%s)
now_s=$(date -d now +%s)
date_diff=$(( (date_s - now_s) / 86400 ))
echo "$website will expire in $date_diff days"
rm "$certificate_file"

答案2

#!/bin/bash

# Based on https://askubuntu.com/questions/1198619/bash-script-to-calculate-remaining-days-to-expire-ssl-certs-in-a-website

### Read Site Certificate and save as File ###
echo -n | openssl s_client -servername $1 -connect $1:443 2>/dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > $1.crt


### Get Full Expiratoin Date ###
date=$(openssl x509 -in $1.crt -enddate -noout | sed "s/.*=\(.*\)/\1/" | awk -F " " '{print $1,$2,$3,$4}')

### Convert Expiration Date in Epoch Format ###
date_s=$(date -j -f "%b %d %T %Y" "$date" "+%s")

### Get Curent Date in Epoch Format ###
now_s=$(date +%s)

### Calculate Time Difference ###
date_diff=$(( (date_s - now_s) / 86400 ))

echo "Certificate for $1 will expire in $date_diff days"

相关内容