research/checking-certificate-expiry-from-the-command-line

Checking Certificate Expiry for a List of Domains from the Command Line

Engineering Note · November 19, 2026 · 10 minute read · OpenSSL · Bash · Node.js · TLS

To check certificate expiry for a list of domains, fetch each certificate with openssl s_client -connect host:443 -servername host </dev/null, pipe it to openssl x509, and use -checkend with a number of seconds to ask whether it expires before your deadline. A 28-line bash loop does this for a whole list and exits non-zero when anything needs attention. Most of the work is in the edge cases: a host that never answers, the wrong certificate, and exit codes that do not mean what you would guess.

Everything below was run with OpenSSL 3.0.13, GNU bash 5.2.21 and Node.js 22.23.4 on Linux, on November 12, 2026. The test servers are local openssl s_server processes with certificates we generated for this note. The outputs are pasted from that run.

What is the one-line check?

For a single host, two commands in a pipe:

openssl s_client -connect 127.0.0.1:8441 -servername soon.test </dev/null 2>/dev/null \
  | openssl x509 -noout -subject -enddate
subject=CN = soon.test
notAfter=Nov 15 20:05:22 2026 GMT

s_client opens a TLS connection and prints the certificate among other text, and openssl x509 prints the fields you ask for. -servername sets SNI (Server Name Indication), the hostname the client sends during the handshake so a server hosting many sites knows which certificate to return. The 2>/dev/null hides connection chatter. If you want a date other tools can parse, add -dateopt iso_8601, which printed notAfter=2026-11-15 20:05:22Z here.

How did we set up certificates to test against?

We made self-signed certificates with openssl req -x509: soon.test with -days 3, long.test with -days 400, and a fallback, default.test, with -days 90.

An already-expired certificate was harder. OpenSSL 3.0.13 has no option on req or x509 to set a start date in the past, and -days -1 is refused as a “Non-positive number”. openssl ca does take explicit dates. We made a throwaway CA with a short config file and signed a request for old.test with -startdate 20250101000000Z -enddate 20251001000000Z:

subject=CN = old.test
notBefore=Jan  1 00:00:00 2025 GMT
notAfter=Oct  1 00:00:00 2025 GMT

Then we started servers on 127.0.0.1: one serving default.test, or soon.test when asked for that name; one each for long.test and the expired old.test; a plain HTTP server; and a Python listener that accepts connections and never answers.

Why do you need -servername?

Here is the same server asked twice, once with SNI and once without:

== with SNI
subject=CN = soon.test
notAfter=Nov 15 20:05:22 2026 GMT
== without SNI
subject=CN = default.test
notAfter=Feb 10 20:05:22 2027 GMT

Without a name, the server returns its default certificate, which expires three months later than the one we care about. According to its help text, OpenSSL 3.0’s s_client sends the -connect hostname as SNI by default, so you only get bitten when you connect by IP address, or when the address you connect to differs from the name on the certificate. Both happen when you check a new server before DNS points at it, or each machine behind a load balancer. Pass -servername every time.

Why does the loop stop after one host?

This is the loop most people write first:

while read -r host port; do
  end=$(timeout 10 openssl s_client -connect "127.0.0.1:$port" -servername "$host" 2>/dev/null \
        | openssl x509 -noout -enddate)
  echo "$host $end"
done < three.txt

The file has three hosts. The output:

soon.test notAfter=Nov 15 20:05:22 2026 GMT

One line and no error. s_client reads from stdin and sends what it reads to the server. Inside a while read loop, stdin is the host list. The first s_client swallowed the other two lines, sent them to the first server, hit end of file and exited, and the loop found nothing left to read. A check that silently skips hosts is worse than no check.

The fix is </dev/null on s_client. It also fixes the one-liner hanging in a terminal. When we fed s_client a pipe that stayed open, openssl x509 printed the date at once, but s_client kept waiting for input until timeout 5 killed it with exit code 124.

What happens when a host never answers?

</dev/null does not help when the server accepts the TCP connection and then says nothing, as our silent Python listener did. s_client was still waiting when timeout 5 killed it. Without a timeout, that check waits forever, and so does everything after it in the list. A refused connection failed in about 30 milliseconds, and a plain HTTP port failed fast with wrong version number. The script below wraps every s_client in timeout 10.

What do -checkend and -checkhost return?

Two exit-code surprises turned up. First, -checkend gives the same answer for “expires soon” and “already expired”:

Certificate will expire
soon exit=1
Certificate will not expire
long exit=0
Certificate will expire
old exit=1

That is with -checkend 2592000 (30 days in seconds). If you want to report expired certificates separately, run -checkend 0 first.

Second, -checkhost prints whether the name matches but exits 0 either way:

Hostname long.test does match certificate
Hostname wrong.test does NOT match certificate
exit=0

So if openssl x509 -checkhost ... is always true. We grep the output for does match instead. A grep for match alone would pass both lines.

What does the full script look like?

#!/usr/bin/env bash
# certcheck.sh DAYS < hosts.txt
# Each line: hostname [port] [address to connect to]. Port defaults to 443.
days=${1:-30}; worst=0
flag() { echo "$1"; (( $2 > worst )) && worst=$2; }

while read -r host port addr; do
  [[ -z $host || $host == \#* ]] && continue
  port=${port:-443}; addr=${addr:-$host}; tag=$(printf '%-24s' "$host:$port")
  pem=$(timeout 10 openssl s_client -connect "$addr:$port" -servername "$host" \
        </dev/null 2>/dev/null | openssl x509 2>/dev/null)
  if [[ -z $pem ]]; then flag "ERROR    $tag no certificate (refused, timed out or not TLS)" 2; continue; fi

  end=$(openssl x509 -noout -enddate <<<"$pem"); end=${end#notAfter=}
  left=$(( ($(date -d "$end" +%s) - $(date +%s)) / 86400 ))
  issuer=$(openssl x509 -noout -issuer -nameopt multiline <<<"$pem" | sed -n 's/^ *commonName *= //p')

  if ! openssl x509 -noout -checkhost "$host" <<<"$pem" | grep -q 'does match'; then
    flag "MISMATCH $tag certificate is not for $host" 2
  elif ! openssl x509 -noout -checkend 0 <<<"$pem" >/dev/null; then
    flag "EXPIRED  $tag expired $end" 1
  elif ! openssl x509 -noout -checkend $(( days * 86400 )) <<<"$pem" >/dev/null; then
    flag "EXPIRING $tag $left days left, $end, issuer: $issuer" 1
  else
    flag "OK       $tag $left days left, $end, issuer: $issuer" 0
  fi
done
exit $worst

The optional third column is the address to connect to. We used it to point test names at local servers; you can use it for one machine behind a load balancer. The exit code is 0 when everything is fine, 1 when something is expiring or expired, and 2 when a host could not be checked or served the wrong certificate. The issuer is printed for a reason the next section shows.

The run against our seven test cases, with a 30-day window:

EXPIRING soon.test:8441           2 days left, Nov 15 20:05:22 2026 GMT, issuer: soon.test
OK       long.test:8442           399 days left, Dec 17 20:05:22 2027 GMT, issuer: long.test
EXPIRED  old.test:8443            expired Oct  1 00:00:00 2025 GMT
MISMATCH wrong.test:8442          certificate is not for wrong.test
ERROR    plain.test:8445          no certificate (refused, timed out or not TLS)
ERROR    silent.test:8446         no certificate (refused, timed out or not TLS)
ERROR    closed.test:8449         no certificate (refused, timed out or not TLS)

real	0m10.605s
exit=2

Each case landed where we expected. The silent host’s 10-second timeout was most of the 10.6 seconds. With only healthy hosts the exit code was 0, and with one expiring host added it was 1.

About the day count: soon.test had 2.99 days left, and bash integer division printed 2. The decision uses -checkend in seconds, so it is exact. With a 2-day window the same certificate came back OK.

What did the public hosts show?

We pointed the script at registry.npmjs.org, pypi.org and github.com, three public hosts our test sandbox can reach. The first line:

EXPIRING registry.npmjs.org:443   28 days left, Dec 11 01:21:42 2026 GMT, issuer: Egress Gateway SDS Issuing CA (production)

The other two showed the same issuer and expiry times within four seconds of it.

These are not those sites’ certificates. Our sandbox sends outbound traffic through a TLS-inspecting gateway, which ends the TLS connection itself and presents a certificate it signs on the spot. To confirm, we asked for a made-up name at an address with nothing behind it:

EXPIRING blackhole.test:443       29 days left, Dec 12 20:08:08 2026 GMT, issuer: Egress Gateway SDS Issuing CA (production)

The gateway minted a 30-day certificate for blackhole.test, so we report no public site’s expiry date here. The same applies behind any corporate proxy doing TLS inspection: the check measures the proxy. Print the issuer, and run the check from a network that reaches the sites directly.

What does the Node.js version look like?

Where Node.js is installed and you would rather not depend on the openssl binary, tls.connect gives the same data:

// node certcheck.mjs DAYS < hosts.txt   (same line format as the bash version)
import tls from 'node:tls';
import { readFileSync } from 'node:fs';

const days = Number(process.argv[2] ?? 30);
const DAY = 86_400_000;

function fetchCert(host, port, addr) {
  return new Promise((resolve, reject) => {
    const sock = tls.connect({ host: addr, port, servername: host, rejectUnauthorized: false });
    sock.setTimeout(10_000, () => sock.destroy(new Error('timed out')));
    sock.once('secureConnect', () => { const c = sock.getPeerCertificate(); sock.end(); resolve(c); });
    sock.once('error', reject);
  });
}

let worst = 0;
for (const line of readFileSync(0, 'utf8').split('\n')) {
  const [host, port = '443', addr = host] = line.trim().split(/\s+/);
  if (!host || host.startsWith('#')) continue;
  const tag = `${host}:${port}`.padEnd(24);
  try {
    const cert = await fetchCert(host, Number(port), addr);
    const left = (Date.parse(cert.valid_to) - Date.now()) / DAY;
    const [status, code] = tls.checkServerIdentity(host, cert) ? ['MISMATCH', 2]
      : left < 0 ? ['EXPIRED', 1] : left < days ? ['EXPIRING', 1] : ['OK', 0];
    console.log(`${status.padEnd(8)} ${tag} ${left.toFixed(1)} days, ${cert.valid_to}, issuer: ${cert.issuer.CN}`);
    worst = Math.max(worst, code);
  } catch (e) {
    console.log(`ERROR    ${tag} ${e.code ?? e.message}`);
    worst = 2;
  }
}
process.exitCode = worst;
EXPIRING soon.test:8441           3.0 days, Nov 15 20:05:22 2026 GMT, issuer: soon.test
OK       long.test:8442           400.0 days, Dec 17 20:05:22 2027 GMT, issuer: long.test
EXPIRED  old.test:8443            -407.8 days, Oct  1 00:00:00 2025 GMT, issuer: Test CA
MISMATCH wrong.test:8442          400.0 days, Dec 17 20:05:22 2027 GMT, issuer: long.test
ERROR    plain.test:8445          ERR_SSL_WRONG_VERSION_NUMBER
ERROR    silent.test:8446         timed out
ERROR    closed.test:8449         ECONNREFUSED

Same verdicts, with better error codes. rejectUnauthorized: false is required: with default settings the expired server fails the handshake with CERT_HAS_EXPIRED and you never see the certificate. With verification off you must check the hostname yourself, which tls.checkServerIdentity does by returning an error on a mismatch. The soon-to-expire certificate shows 3.0 here and 2 in bash because toFixed(1) rounds 2.99 up while bash truncates. Date.parse handled the valid_to string, which uses OpenSSL’s notAfter format.

Limitations

  • We tested only against local servers with certificates we created. Because of the TLS-inspecting gateway described above, we could not observe any real public site’s certificate from this sandbox, and we report none.
  • date -d is GNU date. macOS ships BSD date, which uses different flags. We did not test on macOS.
  • The scripts check the leaf certificate only. An expiring intermediate certificate is not caught.
  • The checks run one host at a time, so each unresponsive host costs the full 10-second timeout. We did not build or test a parallel version.
  • We do not test whether a browser would trust the chain. Our self-signed test certificates passed when their dates and names were fine.

Frequently asked questions

How do I check when a website's SSL certificate expires from the command line?

Run openssl s_client -connect example.com:443 -servername example.com </dev/null 2>/dev/null | openssl x509 -noout -enddate. The first command fetches the certificate and the second prints its notAfter date. The </dev/null matters: without it, s_client waits for input and the command does not return.

What does openssl x509 -checkend do?

It checks whether the certificate will have expired N seconds from now. It exits 0 and prints 'Certificate will not expire' if the certificate is still valid then, and exits 1 and prints 'Certificate will expire' otherwise. An already-expired certificate gets the same exit code and message, so test with -checkend 0 first if you want to tell the two apart.

Why does my certificate check return the wrong certificate?

The server is probably choosing a certificate by SNI, the hostname the client sends during the handshake. If you connect by IP address, or use -noservername, no hostname is sent and many servers return a default certificate. Always pass -servername with the hostname you care about.

Why does a bash loop over a host list stop after the first host?

Because openssl s_client reads stdin, and inside a while-read loop stdin is your host list. It sends the remaining lines to the first server and the loop ends with no error. Redirect s_client's input from /dev/null.

Can I check certificate expiry without OpenSSL installed?

Yes. In Node.js, tls.connect with servername and rejectUnauthorized set to false, followed by getPeerCertificate().valid_to, gives the same date. Setting rejectUnauthorized to false is what lets you read an expired or self-signed certificate instead of getting a CERT_HAS_EXPIRED error. Our 34-line version produced the same verdicts as the bash script.

More from Research

← All research