Day 4: Errors, Logging, Tests – checkcert
Goal: build a tool
checkcertthat checks TLS certificates and reports the remaining validity in days – with a custom exception, logging and a pytest suite of fixtures, parametrize, tmp_path and mocks · Duration: approx. 150 min · Prerequisite: Day 3
Briefing
- Errors are translated at the boundary: socket and SSL exceptions
become a custom
CertError, and the cause is preserved viaraise ... from. logginginstead ofprintfor diagnostics: module logger, level via--verbose, output tostderr.- Exit codes by Nagios convention: 0 OK, 1 WARN, 2 CRIT, 3 ERROR – directly usable in monitoring and CI.
- Tests run without a network: fixtures provide a fixed time and fake certificates, mocks replace sockets.
checkcert host[:port] ... -f hosts.txt
└─ cli.main ──► core.check ──► fetch_cert ──► socket + ssl (handshake, full verification)
│ └─ OSError/SSLError ──► CertError (from err)
└─► Result(status, days) ──► table + exit = worst status
Drill 1: Project and first handshake
cd ~/py-lab
uv init -q --package --name checkcert tag04-checkcert
cd tag04-checkcert
uv add -q typer
uv add --dev pytest pytest-cov ruff
cat >> pyproject.toml <<'EOF'
[tool.ruff.lint]
extend-select = ["E501", "B", "UP", "SIM"]
[tool.pytest.ini_options]
testpaths = ["tests"]
EOFExpected (shortened):
+ coverage==7.16.2
+ pytest==9.1.1
+ pytest-cov==7.1.0
+ ruff==0.17.0
First, by hand, what the tool will later do automatically:
uv run python - <<'EOF'
import socket
import ssl
ctx = ssl.create_default_context()
with (
socket.create_connection(("github.com", 443), timeout=5) as sock,
ctx.wrap_socket(sock, server_hostname="github.com") as tls,
):
cert = tls.getpeercert()
print(tls.version(), tls.cipher()[0])
print(cert["notAfter"])
print(dict(x[0] for x in cert["issuer"])["organizationName"])
print(ssl.cert_time_to_seconds(cert["notAfter"]))
EOFExpected (data changes with every certificate renewal):
TLSv1.3 TLS_AES_128_GCM_SHA256
Nov 29 23:59:59 2026 GMT
Sectigo Limited
1795996799
create_default_context()checks the chain and the hostname against the system CAs. Never setCERT_NONEto work around a problem “real quick”.server_hostnametakes care of SNI and of the hostname check.- The parenthesized
withform opens several contexts and closes them in reverse order.
Save your progress? Sign up for free
Drill 2: Getting to know the errors
uv run python - <<'EOF'
import socket
import ssl
ziele = [("expired.badssl.com", 443), ("gibt-es-nicht.invalid", 443),
("localhost", 1), ("10.255.255.1", 443)]
for host, port in ziele:
try:
ctx = ssl.create_default_context()
with (
socket.create_connection((host, port), timeout=2) as sock,
ctx.wrap_socket(sock, server_hostname=host),
):
pass
except OSError as err:
print(f"{host:<22} {type(err).__name__:<25} {type(err).__mro__[1].__name__}")
EOFExpected:
expired.badssl.com SSLCertVerificationError SSLError
gibt-es-nicht.invalid gaierror OSError
localhost ConnectionRefusedError ConnectionError
10.255.255.1 TimeoutError OSError
Four completely different causes, one common base class:
OSError. The column on the right shows the direct parent
class from the MRO (method resolution order). This gives you the rule
for except: specific before general –
first SSLCertVerificationError (it has a readable
verify_message), then OSError for the rest.
Never a bare except: or except Exception:,
which also swallows programming errors.
Tip: badssl.com deliberately provides broken certificates – ideal for lab tests.
.invalidis reserved by RFC 2606 as a domain that never exists.
Save your progress? Sign up for free
Drill 3: Core module with a custom exception and logging
cat > src/checkcert/core.py <<'EOF'
"""TLS-Zertifikate abrufen und nach Restlaufzeit bewerten."""
import logging
import socket
import ssl
from collections.abc import Callable
from dataclasses import dataclass
from datetime import UTC, datetime
from enum import IntEnum
from typing import Any
log = logging.getLogger(__name__)
PeerCert = dict[str, Any]
Fetcher = Callable[[str, int, float], PeerCert]
class Status(IntEnum):
"""Nagios-Konvention: Wert = Exit-Code."""
OK = 0
WARN = 1
CRIT = 2
ERROR = 3
class CertError(Exception):
"""Zertifikat konnte nicht abgerufen oder geprüft werden."""
@dataclass(frozen=True)
class Result:
host: str
port: int
status: Status
days: int | None = None
expires: datetime | None = None
error: str = ""
def fetch_cert(host: str, port: int = 443, timeout: float = 5.0) -> PeerCert:
"""TLS-Handshake mit voller Prüfung (Kette + Hostname); liefert das Zertifikat."""
ctx = ssl.create_default_context()
try:
with (
socket.create_connection((host, port), timeout=timeout) as sock,
ctx.wrap_socket(sock, server_hostname=host) as tls,
):
log.debug("%s:%s verbunden mit %s", host, port, tls.version())
cert = tls.getpeercert()
except ssl.SSLCertVerificationError as err:
raise CertError(err.verify_message) from err
except OSError as err: # DNS, Timeout, Connection refused, TLS-Fehler
raise CertError(str(err) or type(err).__name__) from err
if not cert:
raise CertError("kein Zertifikat erhalten")
return cert
def expires_at(cert: PeerCert) -> datetime:
"""notAfter ('Nov 29 23:59:59 2026 GMT') als datetime in UTC."""
return datetime.fromtimestamp(ssl.cert_time_to_seconds(cert["notAfter"]), UTC)
def rate(days: int, warn: int = 30, crit: int = 7) -> Status:
if days < crit:
return Status.CRIT
if days < warn:
return Status.WARN
return Status.OK
def check(
host: str,
port: int = 443,
*,
warn: int = 30,
crit: int = 7,
timeout: float = 5.0,
now: datetime | None = None,
fetch: Fetcher = fetch_cert,
) -> Result:
"""Prüft einen Host. Wirft nie – Fehler landen als Status.ERROR im Result."""
try:
expires = expires_at(fetch(host, port, timeout))
except CertError as err:
log.warning("%s:%s nicht prüfbar: %s", host, port, err)
return Result(host, port, Status.ERROR, error=str(err))
days = (expires - (now or datetime.now(UTC))).days
log.debug("%s:%s läuft ab am %s (%d Tage)", host, port, expires, days)
return Result(host, port, rate(days, warn, crit), days, expires)
EOFclass CertError(Exception)with a docstring is enough for a custom exception. Callers only need to know one type instead of seven.raise CertError(...) from errsets__cause__: the traceback shows both errors, tests can check the cause.Status(IntEnum): names for the output, numbers for the exit code, andmax()finds the worst status.log = logging.getLogger(__name__)yields the loggercheckcert.core. Library code only logs; the configuration (level, format) is done by the CLI alone.log.debug("%s:%s ...", host, port)instead of an f-string: the formatting only happens if the level is active.check()getsnowandfetchas parameters. This dependency injection makes the function testable without a network and without a real clock.
Save your progress? Sign up for free
Drill 4: CLI with exit codes
cat > src/checkcert/cli.py <<'EOF'
"""checkcert – Restlaufzeit von TLS-Zertifikaten prüfen (Exit-Code nach Nagios)."""
import logging
from pathlib import Path
from typing import Annotated
import typer
from checkcert.core import Result, Status, check
app = typer.Typer(help=__doc__, add_completion=False)
def parse_target(target: str) -> tuple[str, int]:
"""'host' oder 'host:port' -> (host, port)."""
host, sep, port = target.rpartition(":")
if not sep:
return target, 443
if not port.isdigit():
raise typer.BadParameter(f"ungültiger Port in {target!r}")
return host, int(port)
def read_targets(path: Path) -> list[str]:
"""Eine Adresse pro Zeile; Leerzeilen und #-Kommentare werden ignoriert."""
lines = path.read_text(encoding="utf-8").splitlines()
return [s for line in lines if (s := line.split("#", 1)[0].strip())]
def render(r: Result) -> str:
days = "-" if r.days is None else str(r.days)
expires = f"{r.expires:%Y-%m-%d}" if r.expires else "-"
line = f"{r.status.name:<6} {days:>5} {expires:<10} {r.host}:{r.port}"
return f"{line} ({r.error})" if r.error else line
@app.command()
def main(
targets: Annotated[list[str] | None, typer.Argument(help="host[:port]")] = None,
file: Annotated[
Path | None, typer.Option("--file", "-f", exists=True, help="Hostliste")
] = None,
warn: Annotated[int, typer.Option(help="WARN unter so vielen Tagen")] = 30,
crit: Annotated[int, typer.Option(help="CRIT unter so vielen Tagen")] = 7,
timeout: Annotated[float, typer.Option(help="Sekunden pro Host")] = 5.0,
verbose: Annotated[bool, typer.Option("--verbose", "-v")] = False,
) -> None:
"""Prüft alle Ziele und endet mit dem schlechtesten Status als Exit-Code."""
logging.basicConfig(
level=logging.DEBUG if verbose else logging.ERROR,
format="%(levelname)s %(name)s: %(message)s",
)
all_targets = (targets or []) + (read_targets(file) if file else [])
if not all_targets:
raise typer.BadParameter("mindestens ein Host oder --file angeben")
pairs = [parse_target(t) for t in all_targets] # Fehler vor dem ersten Check
typer.echo(f"{'STATUS':<6} {'TAGE':>5} {'ABLAUF':<10} HOST")
worst = Status.OK
for host, port in pairs:
result = check(host, port, warn=warn, crit=crit, timeout=timeout)
typer.echo(render(result))
worst = max(worst, result.status)
raise typer.Exit(code=int(worst))
EOF
cat > src/checkcert/__init__.py <<'EOF'
"""checkcert – TLS-Zertifikate prüfen."""
from checkcert.cli import app
def main() -> None:
app()
EOF
cat > src/checkcert/__main__.py <<'EOF'
from checkcert import main
main()
EOF
mkdir -p lab
cat > lab/hosts.txt <<'EOF'
# Lab host list: real public test targets
github.com
example.com:443
expired.badssl.com # abgelaufen
wrong.host.badssl.com # falscher Hostname
EOF
uv run checkcert github.com example.com:443; echo "exit=$?"
uv run checkcert -f lab/hosts.txt; echo "exit=$?"Expected (days depend on the date, shortened):
STATUS TAGE ABLAUF HOST
OK 50 2026-11-29 github.com:443
OK 76 2026-12-25 example.com:443
exit=0
STATUS TAGE ABLAUF HOST
OK 50 2026-11-29 github.com:443
OK 76 2026-12-25 example.com:443
ERROR - - expired.badssl.com:443 (certificate has expired)
ERROR - - wrong.host.badssl.com:443 (Hostname mismatch, …)
exit=3
uv run checkcert github.com --warn 60 -v; echo "exit=$?"
uv run checkcert github.com:https; echo "exit=$?"Expected:
STATUS TAGE ABLAUF HOST
DEBUG checkcert.core: github.com:443 verbunden mit TLSv1.3
DEBUG checkcert.core: github.com:443 läuft ab am 2026-11-29 23:59:59+00:00 (50 Tage)
WARN 50 2026-11-29 github.com:443
exit=1
Usage: checkcert [OPTIONS] [targets]...
Try 'checkcert --help' for help.
╭─ Error ──────────────────────────────────────────────────────────────────────╮
│ Invalid value: ungültiger Port in 'github.com:https' │
╰──────────────────────────────────────────────────────────────────────────────╯
exit=2
- A Typer app with only one command needs no subcommand:
checkcert hostinstead ofcheckcert main host. logging.basicConfigonce in the CLI; without-vonly messages fromERRORup appear. Log output goes tostderr, the table tostdout–checkcert ... > report.txtstays clean.rpartition(":")splits at the last colon, which is why::1:8443works too.- All targets are parsed before the first handshake runs: a typo in line 50 of the host list aborts immediately, not after 49 network calls.
Warning: Exit 2 has two meanings: CRIT (Nagios) and usage error (typer). For monitoring that is not a problem – a usage error should trigger an alert there anyway.
Save your progress? Sign up for free
Drill 5: Fixtures, parametrize and mocks
Shared fixtures belong in tests/conftest.py; pytest
loads the file automatically.
mkdir -p tests
cat > tests/conftest.py <<'EOF'
from collections.abc import Callable
from datetime import UTC, datetime
import pytest
from checkcert.core import Fetcher, PeerCert
NOW = datetime(2026, 10, 10, 12, 0, tzinfo=UTC)
@pytest.fixture
def now() -> datetime:
"""Feste Uhrzeit: Tests dürfen nicht vom Kalender abhängen."""
return NOW
@pytest.fixture
def fake_fetch() -> Callable[[str], Fetcher]:
"""Baut einen Fetcher, der ein Zertifikat mit gewünschtem notAfter liefert."""
def make(not_after: str) -> Fetcher:
def fetch(host: str, port: int, timeout: float) -> PeerCert:
return {"notAfter": not_after}
return fetch
return make
EOF
cat > tests/test_core.py <<'EOF'
import logging
import ssl
from datetime import UTC, datetime
from unittest.mock import MagicMock, patch
import pytest
from checkcert.core import CertError, Status, check, expires_at, fetch_cert, rate
@pytest.mark.parametrize(
("days", "expected"),
[
(60, Status.OK),
(30, Status.OK),
(29, Status.WARN),
(7, Status.WARN),
(6, Status.CRIT),
(-1, Status.CRIT),
],
)
def test_rate_grenzen(days, expected):
assert rate(days, warn=30, crit=7) is expected
def test_expires_at_ist_utc():
t = expires_at({"notAfter": "Nov 29 23:59:59 2026 GMT"})
assert t == datetime(2026, 11, 29, 23, 59, 59, tzinfo=UTC)
def test_check_ok(fake_fetch, now):
r = check("lab", fetch=fake_fetch("Nov 29 23:59:59 2026 GMT"), now=now)
assert (r.status, r.days) == (Status.OK, 50)
def test_check_warn_mit_eigener_schwelle(fake_fetch, now):
r = check("lab", warn=60, fetch=fake_fetch("Nov 29 23:59:59 2026 GMT"), now=now)
assert r.status is Status.WARN
def test_check_fehler_wird_error_und_geloggt(caplog, now):
def broken(host: str, port: int, timeout: float) -> dict:
raise CertError("certificate has expired")
with caplog.at_level(logging.WARNING):
r = check("expired.lab", fetch=broken, now=now)
assert r.status is Status.ERROR
assert r.error == "certificate has expired"
assert "expired.lab:443 nicht prüfbar" in caplog.text
def test_fetch_cert_timeout_wird_certerror():
with (
patch("checkcert.core.socket.create_connection", side_effect=TimeoutError),
pytest.raises(CertError, match="TimeoutError") as exc_info,
):
fetch_cert("langsam.lab", timeout=0.1)
assert isinstance(exc_info.value.__cause__, TimeoutError)
def test_fetch_cert_verify_fehler_nutzt_verify_message():
err = ssl.SSLCertVerificationError(1, "certificate verify failed")
err.verify_message = "self-signed certificate"
ctx = MagicMock()
ctx.wrap_socket.side_effect = err
with (
patch("checkcert.core.socket.create_connection"),
patch("checkcert.core.ssl.create_default_context", return_value=ctx),
pytest.raises(CertError, match="^self-signed certificate$"),
):
fetch_cert("selfsigned.lab")
ctx.wrap_socket.assert_called_once()
assert ctx.wrap_socket.call_args.kwargs == {"server_hostname": "selfsigned.lab"}
EOF
uv run pytest -q tests/test_core.py
uv run pytest -v -k rateExpected (shortened):
............ [100%]
12 passed in 0.02s
tests/test_core.py::test_rate_grenzen[60-0] PASSED [ 16%]
tests/test_core.py::test_rate_grenzen[30-0] PASSED [ 33%]
tests/test_core.py::test_rate_grenzen[29-1] PASSED [ 50%]
tests/test_core.py::test_rate_grenzen[7-1] PASSED [ 66%]
tests/test_core.py::test_rate_grenzen[6-2] PASSED [ 83%]
tests/test_core.py::test_rate_grenzen[-1-2] PASSED [100%]
| Tool | What for |
|---|---|
@pytest.fixture |
Test data and setup; the test requests them by parameter name |
@pytest.mark.parametrize |
one test, many cases – ideal for boundary values (30, 29, 7, 6) |
caplog |
captures log messages, caplog.text contains them |
pytest.raises(..., match=) |
expected exception, message as a regex |
unittest.mock.patch |
replaces an object for the duration of the with
block |
MagicMock |
a dummy that records every call
(assert_called_once) |
- The fixture
fake_fetchis a factory: it returns a function that builds the desired fetcher per test. patch("checkcert.core.socket.create_connection", ...)patches where the name is used – in the modulecheckcert.core, not in thesocketmodule itself.side_effect=TimeoutErrormakes the mock raise an exception;return_value=ctxreturns a prepared mock.- The boundary tests document the business rule along the way: at exactly 30 days everything is still OK.
Save your progress? Sign up for free
Drill 6: Testing the CLI with tmp_path, monkeypatch and CliRunner
cat > tests/test_cli.py <<'EOF'
import os
import pytest
import typer
from typer.testing import CliRunner
from checkcert import cli
from checkcert.core import Result, Status
runner = CliRunner()
@pytest.mark.parametrize(
("target", "expected"),
[
("github.com", ("github.com", 443)),
("vault.lab:8200", ("vault.lab", 8200)),
("::1:8443", ("::1", 8443)),
],
)
def test_parse_target(target, expected):
assert cli.parse_target(target) == expected
def test_parse_target_falscher_port():
with pytest.raises(typer.BadParameter):
cli.parse_target("github.com:https")
def test_read_targets(tmp_path):
hosts = tmp_path / "hosts.txt"
hosts.write_text("# Kommentar\n\na.lab\nb.lab:8443 # mit Port\n", encoding="utf-8")
assert cli.read_targets(hosts) == ["a.lab", "b.lab:8443"]
@pytest.fixture
def fake_check(monkeypatch):
"""Ersetzt check() dort, wo cli es benutzt – kein Netzwerk im Test."""
results = {
"ok.lab": Result("ok.lab", 443, Status.OK, 90),
"bald.lab": Result("bald.lab", 443, Status.WARN, 12),
"kaputt.lab": Result("kaputt.lab", 443, Status.ERROR, error="refused"),
}
monkeypatch.setattr(cli, "check", lambda host, port, **kw: results[host])
@pytest.mark.parametrize(
("hosts", "code"),
[(["ok.lab"], 0), (["ok.lab", "bald.lab"], 1), (["bald.lab", "kaputt.lab"], 3)],
)
def test_exit_code_ist_schlechtester_status(fake_check, hosts, code):
result = runner.invoke(cli.app, hosts)
assert result.exit_code == code
def test_ohne_ziele_exit_2():
assert runner.invoke(cli.app, []).exit_code == 2
@pytest.mark.skipif(not os.environ.get("CHECKCERT_LIVE"), reason="nur mit Netz")
def test_live_github():
result = runner.invoke(cli.app, ["github.com"])
assert result.exit_code in (0, 1)
assert "github.com:443" in result.output
EOF
uv run pytest -q -rsExpected:
.........s............ [100%]
=========================== short test summary info ============================
SKIPPED [1] tests/test_cli.py:60: nur mit Netz
21 passed, 1 skipped in 0.05s
tmp_pathprovides a separate empty folder per test – host lists are created there instead of in the repo.monkeypatch.setattr(cli, "check", ...)replacescheckin the modulecli, becauseclibound the name to itself viafrom ... import check. At the end of the test, pytest restores the original.- Fixtures may request other fixtures (
fake_checkusesmonkeypatch), and parametrized tests use fixtures as usual. skipifkeeps slow or network-dependent tests out of the standard run. To check live:
CHECKCERT_LIVE=1 uv run pytest -q -k liveExpected:
. [100%]
1 passed, 21 deselected in 0.06s
Warning:
monkeypatch.setattr(core, "fetch_cert", ...)would have no effect here: the defaultfetch=fetch_certwas bound whencheck()was defined. That is whycheck()injects the fetcher as a parameter.
Save your progress? Sign up for free
Drill 7: The tool is done
uv run pytest -q --cov=checkcert --cov-report=term-missing --cov-fail-under=85
uv run ruff check && uv run ruff format --check
uv run --with mypy mypy --strict src
uv run checkcert -f lab/hosts.txt --timeout 3 > report.txt; echo "exit=$?"
cut -c1-60 report.txt && rm report.txtExpected (shortened):
Name Stmts Miss Cover Missing
---------------------------------------------------------
src/checkcert/__init__.py 3 1 67% 7
src/checkcert/__main__.py 2 2 0% 1-3
src/checkcert/cli.py 35 0 100%
src/checkcert/core.py 52 5 90% 49-50, 55-57
---------------------------------------------------------
TOTAL 92 8 91%
Required test coverage of 85% reached. Total coverage: 91.30%
21 passed, 1 skipped in 0.12s
All checks passed!
8 files already formatted
Success: no issues found in 4 source files
exit=3
STATUS TAGE ABLAUF HOST
OK 50 2026-11-29 github.com:443
OK 76 2026-12-25 example.com:443
ERROR - - expired.badssl.com:443 (certifica
ERROR - - wrong.host.badssl.com:443 (Hostna
term-missing shows the untested lines: the real
handshake (49–50) – covered by the live test – and the special case “no
certificate” (55–57). 100 % is not a goal; the business logic
(rate, check, exit codes) must be covered.
--cov-fail-under turns the threshold into a CI gate.
On Day 5, checkcert becomes an installable package with
versioning, pre-commit and uv tool install.
Save your progress? Sign up for free
Checkpoint
#!/usr/bin/env bash
check() { if eval "$2" >/dev/null 2>&1; then echo "✔ $1"; else echo "✘ $1"; fi; }
cd ~/py-lab/tag04-checkcert
check "Tests grün, Coverage >= 85 %" \
"uv run pytest -q --cov=checkcert --cov-fail-under=85"
check "ruff sauber" "uv run ruff check && uv run ruff format --check"
check "mypy --strict sauber" "uv run --with mypy mypy --strict src"
check "github.com ist OK oder WARN" "uv run checkcert github.com; test \$? -le 1"
check "abgelaufenes Zertifikat gibt Exit 3" \
"uv run checkcert expired.badssl.com; test \$? -eq 3"
check "--warn 400 erzwingt WARN" \
"uv run checkcert github.com --warn 400; test \$? -eq 1"
check "ohne Ziel Exit 2" "uv run checkcert; test \$? -eq 2"
check "Logging nur mit -v" \
"uv run checkcert github.com -v 2>&1 >/dev/null | grep -q DEBUG"Expected:
✔ Tests grün, Coverage >= 85 %
✔ ruff sauber
✔ mypy --strict sauber
✔ github.com ist OK oder WARN
✔ abgelaufenes Zertifikat gibt Exit 3
✔ --warn 400 erzwingt WARN
✔ ohne Ziel Exit 2
✔ Logging nur mit -v
Challenge
A host that runs into a timeout on the first attempt should be retried once – but only on timeouts, never on certificate errors. Prove both with a test, without a network.
Hint: CertError carries the cause in
__cause__; a MagicMock with a list as
side_effect returns the next element on every call.
Solution
In src/checkcert/core.py, check() gets the
parameter retries: int = 1 (after timeout),
and the try block becomes a loop:
for attempt in range(retries + 1):
try:
expires = expires_at(fetch(host, port, timeout))
break
except CertError as err:
if isinstance(err.__cause__, TimeoutError) and attempt < retries:
log.info("%s:%s Timeout, neuer Versuch", host, port)
continue
log.warning("%s:%s nicht prüfbar: %s", host, port, err)
return Result(host, port, Status.ERROR, error=str(err))Append a test to tests/test_core.py:
def test_check_wiederholt_nur_nach_timeout(now):
timeout = CertError("timed out")
timeout.__cause__ = TimeoutError()
fetch = MagicMock(side_effect=[timeout, {"notAfter": "Nov 29 23:59:59 2026 GMT"}])
assert check("wackelig.lab", fetch=fetch, now=now).status is Status.OK
assert fetch.call_count == 2
fetch = MagicMock(side_effect=CertError("certificate has expired"))
assert check("expired.lab", fetch=fetch, now=now).status is Status.ERROR
assert fetch.call_count == 1uv run pytest -q
uv run --with mypy mypy --strict src
uv run checkcert 10.255.255.1 --timeout 0.5 -v 2>&1 | grep -v DEBUGExpected:
22 passed, 1 skipped in 0.20s
Success: no issues found in 4 source files
STATUS TAGE ABLAUF HOST
INFO checkcert.core: 10.255.255.1:443 Timeout, neuer Versuch
WARNING checkcert.core: 10.255.255.1:443 nicht prüfbar: timed out
ERROR - - 10.255.255.1:443 (timed out)
Why is expires guaranteed to be set after the loop?
After a successful fetch, break leaves the loop; every
error path ends with return or continue. mypy
recognizes this and does not report a possibly unbound name.
Save your progress? Sign up for free
Enterprise Note
- Internal hosts often use a CA of their own: set
ssl.create_default_context(cafile=...)orSSL_CERT_FILE– never switch off verification. - Don’t just check the expiry date: full chain, key length, signature
algorithm and SANs. For deeper analysis use
cryptography(x509.load_der_x509_certificate). - Run it as a monitoring check (Nagios/Icinga exit codes) or, better,
as a Prometheus metric
cert_expiry_days; blackbox_exporter can already do that. - Logs structured (JSON) and without secrets; with mTLS never log private keys or passphrases.
- Hundreds of hosts one after another with a 5 s timeout are slow – on
Day 7,
urlcheckchecks in parallel with asyncio.