我在 JSON 證書串列中輸入了帶有資料的資料;我的目標是確定其中哪些已過期,因為我目前正在將其轉換為存盤在 shell 變數中的字串串列,然后嘗試遍歷這些字串,但它無法正常作業:
jsoninput='
[
{"notafter":"1 May 2024 14:21:51 GMT", "subject":"CN=Valid Certificate B"},
{"notafter":"2 Jan 2000 00:00:00 GMT", "subject":"CN=Expired Certificate B"},
{"notafter":"30 Apr 2024 14:21:51 GMT", "subject":"CN=Valid Certificate A"},
{"notafter":"1 Jan 2000 00:00:00 GMT", "subject":"CN=Expired Certificate A"}
]
'
jsondata=$(jq --raw-output 'keys[] as $i | "Certificate \(.[$i].subject): expiryDate: \(.[$i].notafter | strptime("%d %b %Y %H:%M:%S GMT") | mktime )"' <<<"$jsoninput")
nowDate=$(date %s --date='30 days ago')
# this part doesn't work right
for i in $myjsondata; do
if (( $i > $nowDate ));
then echo "Certs are expired!" $i;
else echo "Certs are good" $i;
fi
done
當上面運行時,echo "$jsondata"看起來像:
Certificate CN=Valid Certificate B: expiryDate: 1714576911
Certificate CN=Expired Certificate B: expiryDate: 946771200
Certificate CN=Valid Certificate A: expiryDate: 1714490511
Certificate CN=Expired Certificate A: expiryDate: 946684800
...因此每個證書都有自己的行供for回圈迭代。
顯然,我想要做的是只$i > $nowDate比較該expireyDate欄位,然后能夠根據比較的方式列印描述證書的完整字串;但我不知道如何讓 bash 只看expireyDate.
使用 JQ,我只能決議出 expiryDate 并且作業得很好,但是我得到的輸出是Certs are expired! 1542649223- 沒有列出哪個證書已過期,只有它的過期日期。
如何區分有效證書和過期證書?(作為一個延伸目標,我想對過期的證書進行排序以首先在輸出中列印)。
uj5u.com熱心網友回復:
考慮在 jq 本身內部進行過濾:
jq \
--arg now_epoch "$(date %s --date='30 days ago')" '
($now_epoch | strptime("%s")) as $now
| .[]
| (.notafter | strptime("%d %b %Y %H:%M:%S GMT")) as $expire_time
| if $now > $expire_time
then "Expired cert for \(.subject)"
else "Valid cert for \(.subject)"
end'
輸出為
"Valid cert for CN=Valid Certificate B"
"Expired cert for CN=Expired Certificate B"
"Valid cert for CN=Valid Certificate A"
"Expired cert for CN=Expired Certificate A"
要添加排序,可以將其更改為:
jq -n --arg now_epoch "$(date %s --date='30 days ago')" '
($now_epoch | strptime("%s")) as $now
| [ inputs[]
| (.notafter | strptime("%d %b %Y %H:%M:%S GMT")) as $expire_time
| [ $expire_time,
if $now > $expire_time
then "Expired cert for \(.subject)"
else "Valid cert for \(.subject)"
end
]
]
| sort[]
| .[1]
'
(這肯定比它需要的復雜;如果我沒有時間自己簡化它,我相信 jq-tag 的一位長老會過來并展示如何更簡單地實作這一目標)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/524810.html
標籤:json重击循环jq
