Disc Space Reporter is a lightweight, automated Python utility designed to monitor server hard drive usage and send instant alerts when storage crosses critical thresholds. Keeping tabs on disk capacity is a fundamental task for system administrators, DevOps engineers, and home-lab enthusiasts alike. Without active monitoring, a sudden surge in log files or database growth can quietly fill a drive, causing application crashes, database corruption, and system downtime.
This guide provides a production-ready blueprint to build your own background disk space reporter that dispatches real-time warnings directly to a Discord or Slack webhook. Key Technical Architecture
To keep the footprint minimal and eliminate external binary dependencies, the utility relies on Python’s native standard library alongside psutil for cross-platform hardware metrics.
Metrics Engine: The psutil.disk_usage() module retrieves total, used, and free bytes across targeted mount points.
Notification Layer: Python’s built-in urllib.request handles outbound HTTP POST payloads, avoiding heavier external libraries like requests.
Automation: The script runs continuously in the background as a system service, waking up at defined intervals to sample data. The Complete Python Utility
Save the following script as disc_space_reporter.py. It features customizable thresholds for warning and critical states, adaptive sampling rates, and dual-backend integration for modern chat applications.
import os import shutil import socket import time import json import urllib.request import urllib.error # ==================== CONFIGURATION ==================== # Storage thresholds (Percentage used) THRESHOLD_WARN = 80.0 THRESHOLD_CRIT = 90.0 # Monitoring intervals (Seconds) CHECK_INTERVAL_NORMAL = 3600 # Check hourly under normal conditions CHECK_INTERVAL_ALERT = 300 # Check every 5 minutes if thresholds are breached # Notification Target (Replace with your actual Webhook URL) WEBHOOK_URL = “https://discord.com” # ======================================================= def get_disk_metrics(path=“/”): “”“Fetches human-readable storage data for a specific mount point.”“” total, used, free = shutil.disk_usage(path) percent_used = (used / total)100 # Convert bytes to Gigabytes for readability gb = 1024 ** 3 return { “path”: path, “total_gb”: round(total / gb, 2), “used_gb”: round(used / gb, 2), “free_gb”: round(free / gb, 2), “percent”: round(percent_used, 2) } def build_payload(metrics, status, hostname): “”“Constructs a rich embed payload optimized for Discord/Slack webhooks.”“” color_map = {“CRITICAL”: 15158332, “WARNING”: 15105570, “HEALTHY”: 3066993} payload = { “embeds”: [{ “title”: f”🚨 Storage Alert: {status}“, “color”: color_map.get(status, 0), “fields”: [ {“name”: “Host Machine”, “value”: hostname, “inline”: True}, {“name”: “Mount Point”, “value”: metrics[“path”], “inline”: True}, {“name”: “Usage Percent”, “value”: f”{metrics[‘percent’]}%“, “inline”: False}, {“name”: “Used Space”, “value”: f”{metrics[‘used_gb’]} GB”, “inline”: True}, {“name”: “Available Space”, “value”: f”{metrics[‘free_gb’]} GB”, “inline”: True}, {“name”: “Total Capacity”, “value”: f”{metrics[‘total_gb’]} GB”, “inline”: True} ], “timestamp”: time.strftime(“%Y-%m-%dT%H:%M:%SZ”, time.gmtime()) }] } return json.dumps(payload).encode(‘utf-8’) def dispatch_alert(url, payload): “”“Sends the alert payload over HTTPS without external dependencies.”“” req = urllib.request.Request( url, data=payload, headers={‘Content-Type’: ‘application/json’, ‘User-Agent’: ‘DiscSpaceReporter/1.0’} ) try: with urllib.request.urlopen(req) as response: if response.status in: return True except urllib.error.URLError as e: print(f”Failed to dispatch alert: {e.reason}“) return False def monitor_loop(): “”“Main execution thread handling threshold checks and state management.”“” hostname = socket.gethostname() last_state = “HEALTHY” print(f”Disc Space Reporter initialized. Monitoring host: {hostname}“) while True: metrics = get_disk_metrics() current_percent = metrics[“percent”] # Determine strict status level if current_percent >= THRESHOLD_CRIT: current_state = “CRITICAL” elif current_percent >= THRESHOLD_WARN: current_state = “WARNING” else: current_state = “HEALTHY” # State-transition check prevents notification spamming if current_state != last_state: print(f”State transition detected: {last_state} -> {current_state}“) # Send alert for degraded health states if current_state in [“WARNING”, “CRITICAL”]: payload = build_payload(metrics, current_state, hostname) dispatch_alert(WEBHOOK_URL, payload) last_state = current_state # Dynamically scale polling intervals based on system threat level sleep_duration = CHECK_INTERVAL_ALERT if last_state != “HEALTHY” else CHECK_INTERVAL_NORMAL time.sleep(sleep_duration) if name == “main”: monitor_loop() Use code with caution. Deployment as a Linux System Service
To transform this script into a reliable background daemon that automatically survives system reboots, you can manage it with systemd.
Move the completed script to a secure administrative directory:
sudo mv disc_space_reporter.py /usr/local/bin/disc_space_reporter.py sudo chmod +x /usr/local/bin/disc_space_reporter.py Use code with caution.
Create a brand new configuration file for the service manager: sudo nano /etc/systemd/system/disc-reporter.service Use code with caution. Populate the file with the following unit configuration:
[Unit] Description=Disc Space Reporter Monitoring Agent After=network.target [Service] Type=simple User=root ExecStart=/usr/bin/python3 /usr/local/bin/disc_space_reporter.py Restart=on-failure RestartSec=30 [Install] WantedBy=multi-user.target Use code with caution.
Reload the daemon profiles, register the script to boot on system startup, and launch the service:
sudo systemctl daemon-reload sudo systemctl enable disc-reporter.service sudo systemctl start disc-reporter.service Use code with caution.
You can instantly check the real-time health and execution logging logs of your background reporter by querying the system journal: sudo journalctl -u disc-reporter.service -f Use code with caution. Advanced Extensibility Options
For complex environments, this codebase provides an ideal foundation for further operational engineering adjustments:
Multi-Volume Tracking: Modify the main loop to iterate through an array of explicit paths (e.g., [“/”, “/var/log”, “/mnt/backup”]) instead of querying a single root drive.
Auto-Purge Routines: Trigger an active triage function when CRITICAL status is achieved to automatically wipe legacy log archives or temporary directory structures before human manual intervention is required. If you want, I can expand this utility for you. Tell me:
Do you need integration with a different notification service? Saved time Comprehensive Inappropriate Not working
A copy of this chat, including the images and video, will be included with your feedback A copy of this chat will be included with your feedback
Your feedback will include a copy of this chat and the image from your search
Your feedback will include a copy of this chat, any links you shared, and the image from your search.
Thanks for letting us know
Google may use account and system data to understand your feedback and improve our services, subject to our Privacy Policy and Terms of Service. For legal issues, make a legal removal request.