以前に書いた、ローカルファイルのSSLサーバ証明書有効期限チェックを改修してリモートホストのSSLサーバ証明書有効期限チェックを行なう様に書き直したもの。
#!/bin/bash
sendMail() {
from="$1"
to="$2"
cc="$3"
bcc="$4"
subject="$5"
contents="$6"
inputEncoding="utf-8"
outputEncoding="iso-2022-jp"
subjectHead="=?$outputEncoding?B?"
if [ "$(uname)" == 'Darwin' ]; then
# macOSではechoの-e(エスケープの拡張)オプションはない
subjectBody="`echo "$subject" | iconv -f $inputEncoding -t $outputEncoding | base64 | tr -d '\n'`"
else
subjectBody="`echo -e "$subject" | iconv -f $inputEncoding -t $outputEncoding | base64 | tr -d '\n'`"
fi
subjectTail="?="
fullSubject="$subjectHead$subjectBody$subjectTail"
mailContents="`echo \"$contents\" | iconv -f $inputEncoding -t $outputEncoding`"
cat << __MAIL_CONTENTS__ | /usr/sbin/sendmail -- $to
From: $from
To: $to
Cc: $cc
Bcc: $bcc
Subject: $fullSubject
Mime-Version: 1.0
Content-Type: text/plain; charset=iso-2022-jp
Content-Transfer-Encoding: 7bit
$mailContents
__MAIL_CONTENTS__
return $?
}
TODAY=`date '+%s'`
CHECK_HOSTS="host1.hogehoge.host host2.hogehoge.host host3.hogehoge.host"
WARN_DAYS=1000
MAIL_FROM=no-reply@hogehoge.host
MAIL_TO=admin@hogehoge.host
MAIL_BCC=operator@hogehoge.host
DATA_DIR=/var/tmp
for target_host in ${CHECK_HOSTS}; do
expire_date=`echo | openssl s_client -connect $target_host:443 -servername $target_host 2>/dev/null | openssl x509 -noout -enddate | sed -e 's/notAfter=//'`
echo $expire_date
# dateのオプションはmacOS (BSD)とLinuxで異なるので注意
if [ "$(uname)" == 'Darwin' ]; then
# macOSの場合
expire=`LANG=C date -j -f "%b %d %H:%M:%S %Y %Z" "$expire_date" '+%s'`
else
# Linuxの場合
expire=`date -d "$expire_date\" '+%s'`
fi
if [ $TODAY -gt $expire ]; then
# すでに証明書の期限が切れている
from="$MAIL_FROM"
to="$MAIL_TO"
cc="$MAIL_CC"
bcc="$MAIL_BCC"
subject="SSL証明書の期限が切れています"
contents="サーバー(${target_host})にインストールされているSSL証明書の期限が${expire_date}で切れています。\n至急新しい証明書を取得してインストールしてください。"
echo $subject
echo $cpntents
#sendMail "$from" "$to" "$cc" "$bcc" "$subject" "$contents"
if [ $? -eq 1 ]; then
echo "Send E-Mail failure"
exit 1
fi
echo "Send E-Mail success"
else
# まだ証明書の期限まで日数が残っている
leftdays=$((($expire-$TODAY)/86400))
echo "leftdays:$leftdays"
if [ -f ${DATA_DIR}/${target_host}_cert_leftdays ]; then
# 前回警告を行なった際の有効期限の残日数を取得
prev_leftdays=`cat ${DATA_DIR}/${target_host}_cert_leftdays`
else
prev_leftdays=0
fi
if [ $prev_leftdays -ne $leftdays ]; then
# 前回の警告より残日数が変化していればそれを記録して再度警告
echo $leftdays > ${DATA_DIR}/${target_host}_cert_leftdays
if [ $leftdays -lt ${WARN_DAYS} ]; then
from="$MAIL_FROM"
to="$MAIL_TO"
cc="$MAIL_CC"
bcc="$MAIL_BCC"
subject="SSL証明書の期限が近づいています"
contents="サーバー(${target_host})にインストールされているSSL証明書の期限があと${leftdays}日です。\n期限までに新しい証明書を取得してインストールしてください。"
echo $subject
echo $cpntents
#sendMail "$from" "$to" "$cc" "$bcc" "$subject" "$contents"
if [ $? -eq 1 ]; then
echo "Send E-Mail failure"
exit 1
fi
echo "Send E-Mail success"
fi
fi
fi
done