Home > Mobile >  Date comparison in shell
Date comparison in shell

Time:12-17

This command will list certificates with dates.

keytool -list -v -keystore /path to file/truststore-sit.jks -storepass "password" | grep -e "Alias" -e "Valid" | grep 'until:' | sed 's/^.*until: //'

Output

Wed Feb 15 11:23:46 IST 2023
Thu Jun 22 05:29:59 IST 2023
Sun Oct 02 05:29:59 IST 2033
Mon Feb 12 05:29:59 IST 2024

I need to write a shell script where it can list certificates with dates and comapare them with today's date and list expired certificate and store them a file.

#!/bin/bash
#set -eux
date1=$(keytool -list -v -keystore /path to file/truststore-sit.jks -storepass "password" | grep -e "Alias" -e "Valid" | grep 'until:' | sed 's/^.*until: //')
echo "certificate with date"
$date1

now=$(date  %s)
cond=$(date -d $date1"  %s)

if [ $now -ge  $cond ]
then
    echo True
else
  echo "false"
fi

I need to list the certificates and compare each certificate's date (the 4 dates as mentioned above) with today's date and list only expired certifacte and send a mail message.

CodePudding user response:

Here's an awk for listing the expired certificates from the output of keytool -list -v. Because it's a simple comparison, you don't even need to convert the dates to epoch (which can also be done with any POSIX awk, as long as the dates are in the UTC timezone):

keytool -list -v ... |

awk -F ' (name|from|until): ' -v now="$(date  %Y%m%d%H%M%S)" '

    $1 == "Alias" { alias_name = $2 }

    $1 == "Valid" {

        # $3 -> "Mon Dec 31 14:10:36 UTC 2040"

        split($3,a,/[ :]/)
        a[2] = sprintf("d", (index("JanFebMarAprMayJunJulAugSepOctNovDec",a[2])   2) / 3)

        date = a[8] a[2] a[3] a[4] a[5] a[6]
        if (date <= now)
            print alias_name
    }
'

CodePudding user response:

Here's a quick solution that I came up with that should give you a start:

#!/usr/bin/env bash

keystore="$1"
storepass="$2"
now=$(date  %s)

keytool -list -v -keystore "$keystore" -storepass "$storepass" |
  sed -nr 's/^Alias name:\s*(.*)$/\1/p;s/Valid from:.*until: *(.*)/\1/p' |
  paste - - |
  while IFS=$'\t' read -r alias expires ; do
    expires_at=$(date -d "$expires"  %s)
    if ((expires_at < now)) ; then
      echo -e "$expires\t$alias"
    fi
  done

Just run that script with the keystone file as the first parameter and the password as the second and you should get output similar to:

Tue Apr 06 03:29:40 EDT 2021    debian:sonera_class_2_root_ca.pem
Thu Dec 08 06:10:28 EST 2022    debian:staat_der_nederlanden_ev_root_ca.pem
Wed Mar 25 07:03:10 EDT 2020    debian:staat_der_nederlanden_root_ca_-_g2.pem
Thu Jun 23 20:16:12 EDT 2022    debian:visa_ecommerce_root.pem
  • Related