Skip to main content

Writing a Basic Maintenance Script in Python: Automating a Check Nobody Wants to Do Manually

Updated 6 min readMarkdown
Writing a Basic Maintenance Script in Python: Automating a Check Nobody Wants to Do Manually

Some of the most useful scripts in system administration aren't clever or complex, they're just the thing nobody wants to check manually, every day, forever. Disk space is a perfect example: running out of it can quietly break backups, crash databases, or stall an application with no warning, and the actual check for whether that's about to happen is trivial. This lab worked through writing exactly that kind of script: short, simple, and genuinely useful, a disk usage monitor in Python that reports whether a system is approaching a defined threshold.

Writing the Script

I used nano, a straightforward terminal text editor, to create a new file, diskspace.py, and built it up a few lines at a time.

The script starts by importing shutil, Python's standard library module for high-level file operations, which happens to include disk usage statistics as one of its capabilities:

import shutil

The core logic lives inside a single function:

def check_disk_usage(threshold):
    # Get disk usage details
    total, used, free = shutil.disk_usage("/")

    #Calculate the percentage of disk usage
    usage_percent = (used / total) * 100

    # Notify if usage exceeds the threshold
    if usage_percent > threshold:
        print(f"Warning: Disk usage is at {usage_percent: .2f}%!")
    else:
        print(f"Disk usage is within limits: {usage_percent: .2f}%.")

Every piece here is doing something specific and worth understanding rather than just typing.

shutil.disk_usage("/") queries the root directory specifically and returns three values in a single call: total capacity, space currently used, and space still free. Unpacking all three into named variables at once, rather than querying each separately, is a clean, efficient way to get a complete picture of the disk's state in one line.

The actual percentage calculation, (used / total) * 100, is simple arithmetic, but it's the right abstraction for this problem. Raw byte counts (used vs. total) aren't inherently meaningful to a human reading a report; a percentage is immediately interpretable regardless of how large or small the actual disk happens to be. A script monitoring a 500 GB drive and one monitoring a 2 TB drive can both report in the same, comparable units.

The threshold parameter is what turns this from a one-off disk check into something reusable. Rather than hardcoding a specific percentage inside the comparison logic itself, the function accepts it as an argument, meaning the exact same function can be called with different thresholds for different systems, or different urgency levels, without touching the function's internals at all.

Finally, the script sets a specific value and runs the check:

# Set threshold for disk usage in percentage
threshold = 80 # Adjust as needed
check_disk_usage(threshold)

80% is a reasonable, commonly used default for this kind of alert, high enough that normal day-to-day usage fluctuation won't trigger constant false alarms, low enough that there's still a meaningful buffer of free space left by the time the warning actually fires, time to actually do something about it before the disk is genuinely full.

Running It

After saving the file (Ctrl+X, then Y to confirm, then Enter to confirm the filename) and running it with python3 diskspace.py, the script executed immediately and printed a straightforward result: disk usage was within limits, reported as a specific percentage. No threshold breach, no warning, just a clean confirmation that the system had meaningful headroom left.

Why a Script This Simple Is Genuinely Useful

A few things stood out about why this particular pattern, small, single-purpose, threshold-based, is such a common and practical shape for a maintenance script.

The threshold parameter is what separates a script from a one-off check. Hardcoding if usage_percent > 80 directly inside the comparison would work exactly the same way for a single run, but it locks that specific value into the function's logic itself. Passing it as a parameter means the same underlying check can be reused with a stricter threshold for a critical production system and a looser one for a development machine, without ever touching or duplicating the actual logic.

A percentage, not raw bytes, is the right unit for a human-readable alert. "412 GB used" means very little without immediately knowing the total capacity to compare it against. "53.95% used" is self-contained and instantly interpretable, which matters specifically because the whole point of a script like this is producing output a person (or another automated system) can act on quickly, without needing to do mental math first.

This script, as written, checks once and exits, which is itself an honest and useful starting point. It doesn't run continuously or schedule itself. In a real operational environment, this exact function would typically be wrapped by a scheduler, a cron job on Linux, Task Scheduler on Windows, running it automatically at a set interval, so the check happens on its own without anyone needing to remember to run it. Understanding the core check in isolation first, before adding scheduling on top of it, is the right order to actually learn the underlying logic.

Print statements are a deliberately simple notification mechanism, appropriate for this scale. In a larger operational system, that same threshold breach might trigger an email, a Slack message, or a formal alert in a monitoring platform instead of a console print. The actual detection logic, the comparison against a threshold, stays identical regardless of how the resulting notification eventually gets delivered; only the final print() calls would need to change.

This is a genuinely reusable building block, not just a disk-specific trick. The same threshold-comparison pattern, query a resource's current state, calculate a percentage, compare against a configurable limit, notify accordingly, applies just as well to monitoring CPU load, memory usage, or any other resource with a meaningful upper bound. Disk space is simply a clear, easy-to-understand example of a pattern that shows up constantly across systems monitoring.

This was a short script, barely more than a dozen meaningful lines, but it captures a genuinely useful piece of operational discipline: define what "too much" means as a configurable number, check the actual current state against it, and produce output clear enough that whoever's running it (or whatever automated system eventually calls it on a schedule) knows immediately whether action is needed.

That's really the whole value proposition of basic maintenance scripting. Not solving a hard technical problem, but automating a check that's trivial to perform once and easy to forget to perform consistently, which is exactly the kind of gap where small, well-written scripts like this one earn their keep.

No comments yet. Be the first to comment.