用于检查pem文件证书的Bash脚本,如果过期则发送邮件

时间:2019-05-25 11:39:28

标签: linux bash

有人可以帮助我在bash中完成检查openssl证书的脚本并在过期之前发送邮件吗?我从这里尝试了一些代码,但是我不知道该如何继续

location=/home/merox/Desktop/*.pem ;
server=$HOSTNAME;

for pem in $location; do
   printf '%s: %s\n' \
      certexpire=$(date -d "$(: | openssl x509 -enddate -noout -in "$pem"|cut -d= -f 2)" --iso-8601) \
      "$pem"
done | sort

OUTPUT:
certexpire=2019-05-25: /home/merox/Desktop/key_me.pem
certexpire=2019-05-25: /home/merox/Desktop/key_merox.pem
certexpire=2021-07-14: /home/merox/Desktop/cert_me.pem

2 个答案:

答案 0 :(得分:1)

代码注释。

# So, let's take the files from find and save them in an array
# Using globulation '*' is less secure.
IFS='\n' files=($(find /home/merox/Desktop -mindepth 1 -maxdepth 1 -name '*.pem'))


# one week in seconds
one_week=$((7 * 24 * 60 * 60))
# current time in seconds since epoch
now=$(date "+%s")
# for each file we want to check
for pem in "${files[@]}"; do
   # They expire at this time in seconds since epoch
   expires_at=$(date -d "$(: | openssl x509 -enddate -noout -in "$pem"|cut -d= -f 2)" +%s)
   # the difference
   expires_in=$((expires_at - now))
   # if the will expire in less then one_week
   if (( expires_in < one_week )); then
      # just print them
      printf "%s\n" "$pem"
   fi
done |
sort |
# I leave it to you on how to configure sendmail on your PC
sendmail -v "name@mail.com"

答案 1 :(得分:0)

find: warning: you have specified the -mindepth option after a non-option argument -name, but options are not positional (-mindepth affects tests specified before it as well as those specified after it).  Please specify options before other arguments.

find: warning: you have specified the -maxdepth option after a non-option argument -name, but options are not positional (-maxdepth affects tests specified before it as well as those specified after it).  Please specify options before other arguments.

x509: Cannot open input file /home/merox/Desktop/key_me.pem
/home/merox/Desktop/cert_me.pem
/home/merox/Desktop/key_merox.pem, No such file or directory
x509: Use -help for summary.