diff --git a/cert_checker.py b/cert_checker.py new file mode 100644 index 0000000..94ac283 --- /dev/null +++ b/cert_checker.py @@ -0,0 +1,67 @@ +import os +import subprocess +import json +import re +from datetime import datetime, timedelta + +def get_cert_info(cert_path): + # Use openssl command to get certificate subject and expiration date + openssl_cmd = [ + "openssl", "x509", "-noout", "-subject", "-enddate", "-in", cert_path + ] + process = subprocess.Popen(openssl_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + output, _ = process.communicate() + + if process.returncode == 0: + # Extract domain name and expiration date from openssl output + subject_str, expiration_date_str = map(lambda x: x.split("=", 1)[1].strip(), output.decode("utf-8").split("\n")[:-1]) + domain_name = subject_str.split("/")[0].replace("CN = ","") + expiration_date = datetime.strptime(expiration_date_str, "%b %d %H:%M:%S %Y %Z") + days_remaining = (expiration_date - datetime.now()).days + return {"path": cert_path,"domain": domain_name, "expiration_date": expiration_date_str, "days_remaining": days_remaining} + else: + return None + +def check_and_write_cert_info(directory_path, output_json_path): + cert_info_list = [] + rel_files = [] + for root, _, files in os.walk(directory_path): + #print(files) + for file in files: + cfg = directory_path + file + search_term = "ssl_certificate " + for line in open(cfg, 'r'): + if re.search(search_term, line): + l = line.split() + rel_files.append(l[1].replace(";","")) + if line == None: + print('no matches found') + print(rel_files) + # fullchain_pem_files = [file for file in files if file.lower() == "fullchain.pem"] + + + + for fullchain_pem_file in rel_files: + + fullchain_pem_file = fullchain_pem_file.replace("/data/","/share/docker_data/nginx/data/") + fullchain_pem_file = fullchain_pem_file.replace("/etc/letsencrypt/","/share/docker_data/nginx/letsencrypt/") + print(f"Checking {fullchain_pem_file}") + cert_info = get_cert_info(fullchain_pem_file) + + if cert_info: + cert_info_list.append(cert_info) + + # Write the cert info to a JSON file + with open(output_json_path, 'w') as json_file: + json.dump(cert_info_list, json_file, indent=2) + print(json.dumps(cert_info_list)) + +if __name__ == "__main__": + # Specify the directory path you want to check recursively + directory_to_check = "/share/docker_data/nginx/data/nginx/proxy_host/" + + # Specify the output JSON file path + output_json_path = "/tmp/cert_info.json" + + # Check for fullchain.pem files and write cert info to JSON file + check_and_write_cert_info(directory_to_check, output_json_path)