parsing the date to calculate days until cert expiry from a shell script

Viewed 1019

I would like to get the days until a cert expires. Extracting the dates is easy with openssl

> cat cert | openssl x509 -noout -enddate
notAfter=Jun  8 17:07:09 2021 GMT

Unfortunately parsing the date Jun 8 17:07:09 2021 GMT and finding the days until today is not so straight forward. The goal would be to have

> cat cert | openssl x509 -noout -enddate | ...some commands...
15

Meaning 15 days until the cert expires.

I am aware of the openssl -checkend option, but that is just a boolean and I want the number of days.

2 Answers

You may use this one liner shell script:

expiryDays=$(( ($(date -d "$(openssl x509 -in cert -enddate -noout | cut -d= -f2)" '+%s') - $(date '+%s')) / 86400 ))

Here is the breakup:

  • openssl ... command to print expiry date in notAfter=... format
  • cut -d= -f2 to get text after =
  • date -d ...'+%s'`: to get EPOCH seconds value for expiry date
  • date '+%s': to get EPOCH seconds value for today's date
  • (epochExpiry - epochToday) / 86400: to get difference of 2 EPOCH values as number of days

A quickie perl script using the Date::Parse module (Install through your OS package manager or favorite CPAN client):

#!/usr/bin/env perl
use strict;
use warnings;
use Date::Parse;
use feature qw/say/;

my $certdate = str2time($ARGV[0]);
my $now = time;
my $expiresecs = $certdate - $now;
say int(($expiresecs / (60 * 60 * 24)));

Example:

$ ./showdays "Jun  8 17:07:09 2021 GMT"
67
Related