How to determine SSL cert expiration date from a PEM encoded certificate?

前端 未结 9 2085
感动是毒
感动是毒 2020-11-30 16:21

If I have the actual file and a Bash shell in Mac or Linux, how can I query the cert file for when it will expire? Not a web site, but actually the certificate file itself,

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 16:42

    Here's a bash function which checks all your servers, assuming you're using DNS round-robin. Note that this requires GNU date and won't work on Mac OS

    function check_certs () {
      if [ -z "$1" ]
      then
        echo "domain name missing"
        exit 1
      fi
      name="$1"
      shift
    
      now_epoch=$( date +%s )
    
      dig +noall +answer $name | while read _ _ _ _ ip;
      do
        echo -n "$ip:"
        expiry_date=$( echo | openssl s_client -showcerts -servername $name -connect $ip:443 2>/dev/null | openssl x509 -inform pem -noout -enddate | cut -d "=" -f 2 )
        echo -n " $expiry_date";
        expiry_epoch=$( date -d "$expiry_date" +%s )
        expiry_days="$(( ($expiry_epoch - $now_epoch) / (3600 * 24) ))"
        echo "    $expiry_days days"
      done
    }
    

    Output example:

    $ check_certs stackoverflow.com
    151.101.1.69: Aug 14 12:00:00 2019 GMT    603 days
    151.101.65.69: Aug 14 12:00:00 2019 GMT    603 days
    151.101.129.69: Aug 14 12:00:00 2019 GMT    603 days
    151.101.193.69: Aug 14 12:00:00 2019 GMT    603 days
    

提交回复
热议问题