-
-
Save qfdk/5d703de3b6b085ede2ba4531c7dbc7f8 to your computer and use it in GitHub Desktop.
lua-resty-auto-ssl: Delete expired (or near expired) certs from redis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import redis | |
import json | |
from datetime import datetime, timedelta | |
from redis.exceptions import ResponseError | |
r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True) | |
now = datetime.now() | |
# 过期天数 | |
three_days_from_now = now + timedelta(days=30) | |
keys_to_purge = [] | |
flagged_key_count = 0 | |
valid_key_count = 0 | |
print("") | |
print("======== %s ========" % now.strftime('%m/%d/%Y, %H:%M:%S')) | |
for key in r.scan_iter(): | |
try: | |
cert_data = r.get(key) | |
cert_dict = json.loads(cert_data) | |
# 判断是不是 端口号 | |
if type(cert_dict)!=int: | |
expiry = cert_dict.get('expiry', None) | |
if expiry: | |
key_expires_on = datetime.fromtimestamp(expiry) | |
# Sanity check in case the 'expiry' format changes in the future | |
# Validates timestamp between 2017 - 2030 | |
if expiry < 1500000000 or expiry > 1900000000: | |
raise Exception("Invalid Timestamp Detected. Aborting") | |
if key_expires_on < three_days_from_now: | |
print("Key %s is expiring within 3 days. Adding to purge list" % key) | |
keys_to_purge.append(key) | |
flagged_key_count += 1 | |
else: | |
valid_key_count += 1 | |
except ResponseError: | |
# Wrong datatype - skip | |
# print("Invalid datatype for key ", key) | |
continue | |
except json.decoder.JSONDecodeError: | |
print("Warn: Unable to decode %s. Possibly a challenge key." % key) | |
except Exception as e: | |
print("Failed on Key %s" % key) | |
raise e | |
print("Flagged Key Count:", flagged_key_count) | |
print("Valid Key Count:", valid_key_count) | |
# Purge keys marked to purge, but first, more validation | |
if len(keys_to_purge) > 25: | |
raise Exception("Too many keys (%s) will be purged with this operation. Aborting." % len(keys_to_purge)) | |
else: | |
# Purge Keys | |
for key in keys_to_purge: | |
print("Deleting", key) | |
r.delete(key) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment