Build a Read-Only Linux Disk Capacity Report with Python
Guide tools
Before You Start
Use an unprivileged Linux account with Python 3.10+ and an approved runner to collect data from each host. Choose one expected path per filesystem and confirm mounts with findmnt before reporting. The runner supplies host identity and transport. The script reads only local filesystem state or trusted JSON files.
Procedure
Choose the capacity measures
Start hereTrack space available to unprivileged processes and available inodes. Use the smaller known free percentage for ranking. The example uses a 10 percent threshold as a starting point. This is a snapshot ranking. To estimate time to full, retain samples and validate a growth trend first.
Save the collector and reporting script
Save as capacity.py. Collection prints JSON and emits an error row for a failed path. Reporting reads explicitly supplied host files and marks missing, stale, or unreadable reports. A None percentage indicates an unavailable metric for that filesystem. Use only collector-produced data from your trusted runner.
import argparseimport jsonimport osfrom datetime import datetime, timezonefrom pathlib import Path
def available_percent(available, total): return round(100 * available / total, 1) if total > 0 else None
def collect(paths): rows = [] for path in paths: try: stats = os.statvfs(path) except OSError as exc: rows.append({"path": path, "error": str(exc)}) continue rows.append({ "path": path, "free_bytes": stats.f_bavail * stats.f_frsize, "block_free_pct": available_percent(stats.f_bavail, stats.f_blocks), "inode_free_pct": available_percent(stats.f_favail, stats.f_files), }) print(json.dumps({"utc": datetime.now(timezone.utc).isoformat(), "rows": rows})) return 2 if any("error" in row for row in rows) else 0
def report(files, max_age): now = datetime.now(timezone.utc) results = [] incomplete = False for filename in files: try: data = json.loads(Path(filename).read_text(encoding="utf-8")) stamp = datetime.fromisoformat(data["utc"]) age = (now - stamp).total_seconds() if not 0 <= age <= max_age * 60: raise ValueError("stale report or future timestamp") rows = data["rows"] if not isinstance(rows, list) or not rows: raise ValueError("no filesystem rows") host_rows = [] for row in rows: path = row["path"] if "error" in row: host_rows.append((float("inf"), filename, path, "ERROR", row["error"])) continue blocks = row["block_free_pct"] inodes = row["inode_free_pct"] known = [value for value in (blocks, inodes) if value is not None] rank = min(known, default=float("inf")) state = "LOW" if rank < 10 else "OK" if known else "UNKNOWN" detail = f"free bytes={row['free_bytes']}, blocks={blocks}%, inodes={inodes}%" host_rows.append((rank, filename, path, state, detail)) except (OSError, ValueError, KeyError, TypeError) as exc: incomplete = True print(f"{filename}: NO USABLE REPORT ({exc})") continue results.extend(host_rows) for _, filename, path, state, detail in sorted(results): print(f"{filename} {path}: {state} ({detail})") incomplete |= state in {"ERROR", "UNKNOWN"} return 2 if incomplete else 1 if any(row[3] == "LOW" for row in results) else 0
def main(): parser = argparse.ArgumentParser(description="Collect or report Linux filesystem headroom.") sub = parser.add_subparsers(dest="action", required=True) collector = sub.add_parser("collect") collector.add_argument("paths", nargs="+") aggregator = sub.add_parser("report") aggregator.add_argument("files", nargs="+") aggregator.add_argument("--max-age", type=int, default=15) args = parser.parse_args() if args.action == "collect": if not all(os.path.isabs(path) for path in args.paths): parser.error("collect paths must be absolute") return collect(args.paths) if args.max_age < 1: parser.error("--max-age must be positive") return report(args.files, args.max_age)
if __name__ == "__main__": raise SystemExit(main())Run a local smoke test
Run this from the directory where you saved capacity.py. The first command writes a local report file. Compare the filesystem and free bytes with df. Percentage calculations can differ because df uses its own accounting and rounding rules.
python3 capacity.py collect / > local.jsonpython3 capacity.py report local.jsondf -B1 /df -i /Collect through the approved runner
Run the collect command on each expected host using its normal managed transport. Save stdout under a stable name for each inventory entry, and store the runnerβs transport and timeout status separately. Publish collection files atomically through the runner. Do not treat an old report as evidence that a failed host is reachable.
Report against the complete inventory
List all expected files explicitly rather than globbing only existing files. Replace the example filenames with your inventory paths. When a host is unreachable, the runner should record that cause. The report itself marks the file as unusable and cannot infer why the runner failed.
python3 capacity.py report --max-age 15 local.json node02.jsonVerify healthy, missing, and low-headroom cases
VerifyUse a recent report to check ordinary output, omit an expected file to exercise the unavailable path, and use a disposable JSON fixture with less than 10 percent free to check LOW without filling a filesystem. Exit 0 means complete with no LOW rows, 1 means complete with low headroom, and 2 means incomplete. An incomplete report can still contain LOW rows.
References
Your feedback keeps these production procedures accurate and battle-tested.