Lab — Python Certificate Expiry Monitor¶
Lab Overview¶
Purpose: Detect certificates nearing expiry before browsers and API clients fail.
Scenario: An e-commerce edge cert expired overnight. Leadership wants a Python monitor with days-left reporting.
Expected outcome: CLI checks PEM fixtures and optional live TLS endpoints; exits 1 when below threshold.
This is a lab, not a tutorial
Apply REST APIs and Error Handling.
Business Scenario¶
Platform runs dozens of public hostnames. Manual calendar reminders failed; you need automation that CI and cron can run.
Learning Objectives¶
- Parse PEM with
cryptographyorssl+datetime - Compute days remaining in UTC
- Support
--fixturePEMs when network is blocked - Threshold exit codes for alerting
Prerequisites¶
Knowledge¶
Software¶
| Tool | Notes |
|---|---|
| cryptography | recommended |
| openssl | to mint lab PEMs |
Estimated cost: £0.
Environment¶
mkdir -p ~/rebash-lab-python-certs/{fixtures,out}
cd ~/rebash-lab-python-certs
python3 -m venv .venv && source .venv/bin/activate
pip install 'cryptography>=42,<45'
Initial State — create short-lived and long-lived PEMs¶
openssl req -x509 -newkey rsa:2048 -keyout fixtures/key.pem -out fixtures/soon.pem \
-days 5 -nodes -subj "/CN=soon.example.test" 2>/dev/null
openssl req -x509 -newkey rsa:2048 -keyout /tmp/k2.pem -out fixtures/later.pem \
-days 365 -nodes -subj "/CN=later.example.test" 2>/dev/null
Task¶
Create cert_monitor.py:
--pem fixtures/soon.pem/ multiple paths--warn-days 14— exit1if any cert expires within N days- Write
out/report.jsonwithnot_afteranddays_left - Optional
--host example.com:443usingssl.get_server_certificate(skip if offline)
Validation¶
python cert_monitor.py --pem fixtures/soon.pem --pem fixtures/later.pem --warn-days 14; echo $? # 1
python -c 'import json; print(json.load(open("out/report.json")))'
-
soon.pemtriggers warning with--warn-days 14 - Report JSON lists both certs when both passed
- Invalid PEM exits
2
Troubleshooting¶
| Symptom | Fix |
|---|---|
| openssl missing | Install or download sample PEMs from course assets |
| Timezone confusion | Always use aware UTC datetimes |
Cleanup¶
Production Discussion¶
Prefer ACME automation (Let’s Encrypt) and cloud-managed certs. This monitor is a safety net, not a replacement for auto-renewal.
Related¶
- Next: Slack Notification Bot