script to check if SSL certificate is valid

Your command would now expect a http request such as GET index.php for example. Use this instead:

if true | openssl s_client -connect www.google.com:443 2>/dev/null | \
  openssl x509 -noout -checkend 0; then
  echo "Certificate is not expired"
else
  echo "Certificate is expired"
fi

  • true: will just give no input followed by eof, so that openssl exits after connecting.
    • openssl ...: the command from your question
    • 2>/dev/null: error output will be ignored.
  • openssl x509: activates X.509 Certificate Data Management.
    • This will read from standard input defaultly
    • -noout: Suppresses the whole certificate output
    • -checkend 0: check if the certificate is expired in the next 0 seconds

It does get you the certificate, but it doesn't decode it. Since that would be needed if you want the date, you don't see it. So what's needed is that you pipe it into OpenSSL's x509 application to decode the certificate:

openssl s_client -connect www.example.com:443 \
    -servername www.example.com </dev/null |\
    openssl x509 -in /dev/stdin -noout -text

This will give you the full decoded certificate on stdout, including its validity dates.


If you need to check expiry date, thanks to this blog post, found a way to find this information with other relevant information with a single call:

echo | openssl s_client -servername unix.stackexchange.com -connect unix.stackexchange.com:443 2>/dev/null | openssl x509 -noout -issuer -subject -dates

The output includes issuer, subject (to whom the certificate is issued), date of issued and finally date of expiry:

issuer= /C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert SHA2 High Assurance Server CA
subject= /C=US/ST=NY/L=New York/O=Stack Exchange, Inc./CN=*.stackexchange.com
notBefore=May 21 00:00:00 2016 GMT
notAfter=Aug 14 12:00:00 2019 GMT