Python for IT Automation

The fastest way to waste time learning a programming language is staying trapped in tutorial exercises that never touch a real machine. The fastest way to actually master Python is to point it at problems you run into in your own hardware, network, and daily routine.

For me, Python isn’t about building bloated web backends—it’s practical IT glue. Whenever a manual check becomes repetitive, fragile, or too important to leave to chance, it gets turned into a script.


1. Real-World First Win: Automated Thermal Shutdown

Running a dedicated Linux server alongside a Raspberry Pi 4 and Raspberry Pi 5 means equipment stays powered on 24/7, often unattended. If a cooling fan seizes, ambient room temperature spikes, or a heatsink gets choked with dust, thermal throttling isn’t the worst-case scenario—hardware failure or an electrical fire hazard is.

Waiting until you notice a dropped SSH session is too late. So I put Python in charge of watching thermals directly from the Linux kernel’s sysfs interface (/sys/class/thermal/) with zero third-party pip dependencies.

Avoiding False Positives

A naive watchdog that powers off a server on the very first spike above 80°C will shut down your box during a legitimate compile job or backup compression. A reliable thermal watchdog needs:

  1. Multi-sample confirmation: Require N consecutive readings above the threshold before acting.
  2. Audit logging: Write warnings to journald/syslog before shutting down so you know why a node powered off.
  3. Graceful poweroff: Call systemctl poweroff so filesystems, containers, and RAID volumes sync cleanly rather than cutting power mid-write.
#!/usr/bin/env python3
"""Thermal watchdog for Linux hosts and Raspberry Pi nodes."""

from pathlib import Path
import logging
import subprocess
import time

THERMAL_ZONES = sorted(Path("/sys/class/thermal").glob("thermal_zone*/temp"))
MAX_TEMP_C = 82.0
CHECK_INTERVAL_SEC = 10
STRIKE_LIMIT = 3

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
)


def read_max_temp_c() -> float:
    temps = []
    for zone in THERMAL_ZONES:
        try:
            millidegrees = int(zone.read_text().strip())
            temps.append(millidegrees / 1000.0)
        except (OSError, ValueError):
            continue
    if not temps:
        raise RuntimeError("No readable thermal zones found")
    return max(temps)


def main() -> None:
    strikes = 0
    while True:
        temp_c = read_max_temp_c()
        if temp_c >= MAX_TEMP_C:
            strikes += 1
            logging.warning(
                "High temp detected: %.1f°C (strike %d/%d)",
                temp_c,
                strikes,
                STRIKE_LIMIT,
            )
            if strikes >= STRIKE_LIMIT:
                logging.critical(
                    "Thermal threshold %.1f°C sustained. Initiating safe shutdown.",
                    MAX_TEMP_C,
                )
                subprocess.run(["systemctl", "poweroff"], check=False)
                return
        else:
            if strikes > 0:
                logging.info("Temp normalized: %.1f°C. Resetting strikes.", temp_c)
            strikes = 0

        time.sleep(CHECK_INTERVAL_SEC)


if __name__ == "__main__":
    main()

Deployed under a minimal systemd unit across the server and both Pis, every node monitors itself autonomously and protects the hardware even if the network goes down.


2. Next Target: Networking & Homelab Automation

Once you build one script that genuinely protects your infrastructure, you start seeing automation opportunities everywhere on the network:


3. Lifestyle, Teaching & Everyday Tooling

The same mindset applies well outside the server closet. As I keep applying Python to more of what I do day to day, the goal is stripping friction out of routine tasks:


Learn by Solving Real Problems

You don’t need to memorize every standard library module before writing useful code. Pick a real problem—protecting hardware from heat, verifying backups, or automating a daily chore—build the simplest script that handles edge cases cleanly, and iterate from there.

Every manual task you repeat twice is a candidate for a fifty-line Python script.

Related
Python · Automation · Homelab · Linux