Skip to content

Instantly share code, notes, and snippets.

@nabe-abk
Last active January 27, 2020 06:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nabe-abk/dd971ac01c57dadaf8a2a761ad022e02 to your computer and use it in GitHub Desktop.
Save nabe-abk/dd971ac01c57dadaf8a2a761ad022e02 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
#-----------------------------------------------------------------------------
# Check SSL expiration
# (C)2019-2020 nabe / nabe@abk
#-----------------------------------------------------------------------------
# ./check_SSL_expiration.pl [-s] [notify_address]
# -s silent mode
#-----------------------------------------------------------------------------
use strict;
use Time::Local;
#-----------------------------------------------------------------------------
my @domains = qw(
ssl.example.com
ssl.example.jp
);
my $cmd = "openssl s_client -connect %d:443 < /dev/null 2>&1 | openssl x509 -text | grep 'Not After' |";
my $notify_days = 100; # alarm expiration days
my $silent = ($ARGV[0] eq '-s') && shift(@ARGV);
my $notify_mail = shift(@ARGV); # alarm mail
#-----------------------------------------------------------------------------
my $response;
my $min_days = 9999;
my $tm = time();
foreach(@domains) {
my $c = $cmd;
$c =~ s/%d/$_/;
open(my $fh, $c);
my $not_after = <$fh>;
close($fh);
my $result = "error!";
# ex) Nov 22 04:55:25 2019 GMT
# ex) Apr 9 19:04:27 2020 GMT
if ($not_after =~ /([A-Z]\w\w) ([ \d]?\d) (\d+):(\d+):(\d+) (\d+)/) {
my $x = int(index(" JanFebMarAprMayJunJulAugSepOctNovDec", $1)/3);
if ($x) {
my $diff = timegm($5, $4, $3, $2, $x-1, $6) - $tm;
my $days = int($diff / 86400);
if ($days < $min_days) {
$min_days = $days;
}
$x = substr("0$x",-2);
my $date = "$6/$x/$2 $3:$4:$5";
$result = "$date\t$days days";
}
}
my $dom = substr($_ . " " x 15, 0, 15);
$response .= "\t$dom\t$result\n";
!$silent && print "\t$dom\t$result\n"
}
#-----------------------------------------------------------------------------
if ($notify_mail eq '' || $notify_days < $min_days) {
exit(0);
}
#-----------------------------------------------------------------------------
# send mail
#-----------------------------------------------------------------------------
my $sendmail_cmd;
foreach(qw(/usr/sbin /usr/bin /usr/lib)) {
if (-x "$_/sendmail") { $sendmail_cmd = "$_/sendmail"; last; }
}
open(my $fh, "| $sendmail_cmd -t -i");
print $fh "To: $notify_mail\n";
print $fh "Subject: Notify SSL expiration: $min_days days\n";
print $fh "\n\n";
print $fh $response;
close($fh);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment