Python automation often has to run other programs: systemctl, rsync, ssh, kubectl. The subprocess module does it safely when you pass arguments as a list, check the exit code, capture output, and set a timeout. Around it sit os, shutil, and signal for files, processes, and clean shutdowns. This lesson builds a maintenance job that restarts services across a fleet, and shows the two ways such jobs become dangerous: shell=True with outside input, and a call with no timeout that hangs forever.
Difficulty: Intermediate · Know this first: Lesson 38, Lesson 26
This bar adds up minutes for the maintenance job across the fleet. It is a worked example, not a measurement. The timeout and shell hops are where automation becomes a risk.
Pick a hostname from the inventory and how the command is run. See what actually executes.
Injected: the shell interprets ; and $( ) inside the hostname
Three questions. No score is saved anywhere — this is just you against the material.
System automation in Python grows in four levels: running commands, running them safely, running them across a fleet, and choosing the right tool.
At the basic level you run programs and check them.
subprocess.run([...], capture_output=True, text=True, check=True).result.returncode, result.stdout, result.stderr.shutil.which() to find a program.Where it breaks: passing one string without shell=True, so Python looks for a program literally named "ls -l".
Try it: Basic
subprocess.run("ls -l") raises FileNotFoundError. Why?
Now do it: Run uname -a from Python with a list and print stdout.
At the intermediate level every call is safe and bounded.
shell=True with outside data; validation with re.fullmatch.timeout= on every call; TimeoutExpired and CalledProcessError handled per item.env, cwd, LC_ALL=C for parsed output.Try it: Intermediate
You must run a shell pipeline (sort | uniq -c). What is the safest way?
Now do it: Replace one shell pipeline in a script with Python code.
At the advanced level jobs run on many hosts safely.
concurrent.futures.ThreadPoolExecutor for parallel ssh with a bounded pool.Try it: Advanced
Restarting 500 hosts in parallel took the service down. What should the job do?
Now do it: Add a batch size and a stop-after-N-failures option to one fleet script.
At the master level you know when not to write the script.
Trade-off: a short Python script is quick and fully under your control, and slowly re-implements inventory, retries, and reporting that existing tools already have.
Try it: Master
Your Python script now has inventory parsing, parallel ssh, retries, dry runs, and reports. What should you consider?
Now do it: List the features of one of your automation scripts that Ansible provides out of the box.
A safe fleet helper: validated inputs, list arguments, timeouts, checked exit codes, bounded parallelism, and a summary.
import re, subprocess, sys
from concurrent.futures import ThreadPoolExecutor, as_completed
HOST_RE = re.compile(r"[a-z0-9][a-z0-9.-]{0,62}")
SSH = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "-o", "ServerAliveInterval=15"]
def run_on(host, *cmd, timeout=120):
if not HOST_RE.fullmatch(host):
raise ValueError(f"refusing suspicious hostname {host!r}")
return subprocess.run([*SSH, host, *cmd], capture_output=True, text=True,
timeout=timeout, check=True, env={"LC_ALL": "C", "PATH": "/usr/bin:/bin"})
def restart(host, unit):
try:
run_on(host, "sudo", "systemctl", "restart", unit)
state = run_on(host, "systemctl", "is-active", unit).stdout.strip() # verify, do not assume
return host, "changed" if state == "active" else "failed", state
except subprocess.TimeoutExpired:
return host, "failed", "timeout"
except subprocess.CalledProcessError as e:
return host, "failed", e.stderr.strip()[-200:]
except ValueError as e:
return host, "failed", str(e)
hosts = [h.strip() for h in open("hosts.txt", encoding="utf-8") if h.strip()]
results = []
with ThreadPoolExecutor(max_workers=8) as pool: # bounded parallelism
futures = [pool.submit(restart, h, "app.service") for h in hosts]
for f in as_completed(futures):
results.append(f.result())
for host, state, note in sorted(results):
print(f"{host:<20} {state:<8} {note}", file=sys.stderr)
sys.exit(1 if any(s == "failed" for _, s, _ in results) else 0)
This is a composite of a failure pattern that keeps repeating; the details are illustrative. An inventory entry deleted the backups.
shell=True is banned by a lint rule in the automation repository, hostnames are validated against a pattern, the inventory is validated in CI, and the automation account cannot write to the backup directory.
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Type each one, read what it prints, and compare it with the note above it.
A list passes the semicolon as part of one argument; a shell runs it.
python3 -c "import subprocess; host = 'web12; echo INJECTED'; subprocess.run(['echo', 'restart', host]); subprocess.run(f'echo restart {host}', shell=True)"check=True turns a failed command into an exception.
python3 -c "import subprocess
try:
subprocess.run(['ls', '/nope'], check=True, capture_output=True, text=True)
except subprocess.CalledProcessError as e:
print('failed with', e.returncode, '-', e.stderr.strip())"A timeout stops a command that hangs.
python3 -c "import subprocess
try:
subprocess.run(['sleep', '30'], timeout=1)
except subprocess.TimeoutExpired as e:
print('stopped after', e.timeout, 's')"Cron is not your shell: the same command with an empty environment.
env -i /usr/bin/python3 -c "import os, shutil; print('PATH =', os.environ.get('PATH')); print('which systemctl:', shutil.which('systemctl'))"safe_runner.pyThis program validates hostnames, builds list arguments, and enforces a timeout and exit-code check for each host, using harmless local commands in place of ssh. Save it as safe_runner.py, then run it.
# safe_runner.py
import re, subprocess, sys
HOST_RE = re.compile(r"[a-z0-9][a-z0-9.-]{0,62}")
inventory = ["web01", "web02", "web12; rm -rf /var/backups #", "slow01", "bad01"]
COMMANDS = { # stand-ins for: ssh HOST sudo systemctl restart app
"slow01": [sys.executable, "-c", "import time; time.sleep(5)"],
"bad01": [sys.executable, "-c", "import sys; sys.exit(3)"],
}
for host in inventory:
if not HOST_RE.fullmatch(host):
print(f"{host[:22]:<22} REJECTED: not a valid hostname, nothing run")
continue
cmd = COMMANDS.get(host, [sys.executable, "-c", f"print('restarted app on {host}')"])
try:
r = subprocess.run(cmd, capture_output=True, text=True, timeout=1, check=True)
print(f"{host:<22} ok: {r.stdout.strip()}")
except subprocess.TimeoutExpired:
print(f"{host:<22} FAILED: timed out after 1 s, moved on")
except subprocess.CalledProcessError as e:
print(f"{host:<22} FAILED: exit code {e.returncode}")
Run it, and you should see this output:
$ python3 safe_runner.py web01 ok: restarted app on web01 web02 ok: restarted app on web02 web12; rm -rf /var/bac REJECTED: not a valid hostname, nothing run slow01 FAILED: timed out after 1 s, moved on bad01 FAILED: exit code 3
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/python-subprocess-and-system-automation && cd ~/labs/python-subprocess-and-system-automation) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "Python subprocess and System Automation", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'A list passes the semicolon as part of one argument; a shell runs it.'
'check=True turns a failed command into an exception.'
'A timeout stops a command that hangs.'
'Cron is not your shell: the same command with an empty environment.'
)
step_1() {
python3 -c "import subprocess; host = 'web12; echo INJECTED'; subprocess.run(['echo', 'restart', host]); subprocess.run(f'echo restart {host}', shell=True)"
}
step_2() {
python3 -c "import subprocess
try:
subprocess.run(['ls', '/nope'], check=True, capture_output=True, text=True)
except subprocess.CalledProcessError as e:
print('failed with', e.returncode, '-', e.stderr.strip())"
}
step_3() {
python3 -c "import subprocess
try:
subprocess.run(['sleep', '30'], timeout=1)
except subprocess.TimeoutExpired as e:
print('stopped after', e.timeout, 's')"
}
step_4() {
env -i /usr/bin/python3 -c "import os, shutil; print('PATH =', os.environ.get('PATH')); print('which systemctl:', shutil.which('systemctl'))"
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
echo.Write a job that rotates a TLS certificate across 60 web servers: copy the new files, check them, reload nginx, and verify the served certificate.
How are hostnames validated? What runs on each host, and with what timeouts? How many hosts change at once, and what stops the rollout? What makes it safe to run twice?
Say 60 hosts, a 30-second budget per host, and at most 3 failed hosts before stopping.
Hosts validated by pattern; scp and ssh with list arguments, BatchMode, and ConnectTimeout; per host: compare the served fingerprint first (skip if already new), copy, nginx -t, reload, verify with ssl from Python; batches of 5 with a failure budget of 3; SIGTERM finishes the current batch; a JSON summary on stdout.
Small batches are safe and slow; large batches are fast and risk many hosts at once. Checking the served certificate first makes the job idempotent at the cost of an extra connection per host.