与Epoch的日期比较,在Bash脚本中找到有效期


#!/bin/bash
for ADDR in `netstat -plant|grep LISTEN|grep http|awk '{print $4}'|egrep -v ':80$|:5555$'|sort -u`; do
  EXPDATE=`openssl s_time 2>/dev/null | openssl s_client -connect $ADDR 2>/dev/null | openssl x509 -dates 2>/dev/null | grep ^notA | cut -f2 -d= | sed -e "s/ GMT//"`
  printf "ttt|%st|%st|t%st|n" "$ADDR" "$EXPDATE"
done
EXPDATES="$(echo "$EXPDATE" | awk '{print $1,$2,$4,$3}')"
CURREPOCH="$(date +%s)"
for i in "$EXPDATES"; do
  CREXPEPOCH="$(date +%s -d "$i")"
  if [[ "$CURREPOCH" -gt "$CREXPEPOCH" ]]; then
    echo "No Expiry Found."
  else
    echo "Cert expired"
  fi
done

在这里,我从具有多个日期值的expdate获得了日期,如下所示,

Jul 12 12:00:00 2019
Jun 18 12:00:00 2019
May  8 00:00:00 2018
Nov 14 00:00:00 2017

,然后转换为时期时间,以更好地与当前时期进行比较。

如果发现了任何过去的日期,则脚本应返回"过期",否则"找不到有效期"。

我尝试过上面的脚本,这是不起作用的。

我该怎么做?有帮助吗?

以下轨道在数组中的内容,而不是试图滥用字符串。

#!/usr/bin/env bash
# return all addresses that smell like HTTP
get_addrs() {
  netstat -plant 
  | awk '/LISTEN/ && /http/ && ! ($4 ~ /:(80|5555)$/) { print $4; }' 
  | sort -u
}
# Given a local server address, return a usable client address
# converts wildcard addresses to loopback ones.
clientAddr() {
  local addr=$1
  case $addr in
    0.0.0.0:*) addr=127.0.0.1:${addr#0.0.0.0:} ;;
    :::*)      addr='localhost:'"${addr#:::}"  ;;
  esac
  printf '%sn' "$addr"
}
# Given a local address that runs a HTTPS server, return the last valid date for its certificate
endDateForAddr() {
  local addr endDate
  addr=$(clientAddr "$1") || return
  endDate=$(openssl s_client -connect "${addr}" </dev/null 2>/dev/null 
            | openssl x509 -dates 
            | awk -F= '/^notAfter/ { print $2; exit }')
  [[ $endDate ]] && printf '%sn' "$endDate"
}
# Loop over our local HTTPS services...
expDates=( )
while read -r addr; do
  # find an address we can use to refer to each...
  addr=$(clientAddr "$addr") || continue
  # ...and use that to find its certificate expirey date.
  result=$(endDateForAddr "$addr") || continue
  # then add that to our array.
  expDates+=( "$result" )
done < <(get_addrs)
# in bash 4.3, this is more efficiently written: printf -v curr_epoch '%(%s)T' -1
curr_epoch="$(date +%s)"
for expdate in "${expDates[@]}"; do
  exp_epoch=$(date +%s -d "$expdate")
  if (( curr_epoch > exp_epoch )); then
    echo "$expdate is in the past"
  else
    echo "$expdate is in the future"
  fi
done

...其输出(截至撰写本文时正确):

Jul 12 12:00:00 2019 is in the future
Jun 18 12:00:00 2019 is in the future
May  8 00:00:00 2018 is in the future
Nov 14 00:00:00 2017 is in the future

最新更新