4

检查证书是否过期的脚本

 9 months ago
source link: https://bajie.dev/posts/20231212-check_ssl/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

检查证书是否过期的脚本

2023-12-12 1 分钟阅读

证书会经常面临过期而没有及时续费的情况,写个脚本提醒一下自己吧:

crontab -l

0 8 * * * /usr/local/bin/check_ssl.sh www.ddky.com

check_ssl.sh的内容:

#!/bin/bash
# Print the number of days till certificate expiration
#
# Example:
#   $ check_cert.sh sleeplessbeastie.eu
#   81
#   $ check_cert.sh lwn.net
#   630
#
# Exit codes:
#   0   - certificate is not expired
#   1   - certificate is     expired
#   254 - certificate is empty
#   255 - DNS resolution failed
#

# temporary file to store certificate
certificate_file=$(mktemp)

# delete temporary file on exit
trap "unlink $certificate_file" EXIT

if [ "$#" -eq "1" ]; then
  website="$1"
  host "$website" >&-
  if [ "$?" -eq "0" ]; then
    echo -n | openssl s_client -servername "$website" -connect "$website":443 2>/dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > $certificate_file
    certificate_size=$(stat -c "%s" $certificate_file)
    if [ "$certificate_size" -gt "1" ]; then
      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 "$date_diff"
      if [ "$date_diff" -le 37 ]; then
          /usr/local/bin/mailsend -q -to "[email protected]" -from [email protected] -ssl -port 465 -auth -auth-plan -smtp smtp.exmail.qq.com -sub "证书就要到期了" -v -user "[email protected]" -pass "xxxxxxxx" -cs "utf-8" -enc-type "base64" -M "$website 还有 $date_diff 天就要到期了!!!"
      fi
      if [ "$date_s" -gt "$now_s" ]; then
        exit 0 # ok
      else
        exit 1 # not ok
      fi
    else
      exit 254
    fi
  else
    exit 255
  fi
fi

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK