9.3 Python Fundamentals for Linux System Administration
Key Takeaways
Check the host’s Python version and package ownership. Install project dependencies with that project’s virtual-environment interpreter.
Choose data structures by order, mutability and lookup needs. Dictionary get distinguishes absent keys from keys present with a None value.
Use standard-library modules for paths, structured data, subprocesses and filesystem evidence.
Pass external command arguments as distinct elements and validate them. Text decoding, captured output and nonzero-status checks are independent options.
Follow PEP 8 and the project’s established conventions. Report failures at the boundary where they can be interpreted.
Python for Linux System Administration
Use Python 3 when an administrative task benefits from structured input, reusable logic or targeted exception handling. Use the interpreter supported by the host and the application. For example, Debian 12 shipped Python 3.11 and uses an externally managed system environment. RHEL 9 ships Python 3.9 as its default and offers additional versioned interpreters on applicable releases. Check python3 --version and the distribution's package documentation. Python upstream and distribution vendors have separate support lifecycles.
Project dependencies and virtual environments
An operating system package manager owns the distribution’s Python packages. Use it for system integration. Python package tooling can install an application’s separately declared dependencies into a project environment. The externally managed environment specification tells installers such as pip to refuse default installs into a marked interpreter outside a virtual environment. Behavior depends on how that interpreter is packaged. Check the error and the installed interpreter before acting.
On a lab Linux host where venv and its pip support are installed, work in a project directory you can write:
python3 -m venv .venv
.venv/bin/python -m pip --version
.venv/bin/python -m pip install -r requirements.txt
.venv/bin/python -m pip check
Use a reviewed requirements file and approved package source. The environment has separate package paths by default, with a copy or link to the interpreter and a configuration that ties it to the base installation. It is not an operating-system sandbox. source .venv/bin/activate adjusts the shell’s PATH, and deactivate undoes activation. Activation is optional when the command uses the environment’s interpreter directly. If a distribution splits support for venv into another package, install the matching OS package. Recreate the environment when moving it.
Use python -m pip list to inspect the current environment, python -m pip show NAME to see a package’s metadata, and python -m pip freeze to record installed versions in requirements syntax. Freeze reports what is installed. Recreating it on a different Python release or platform depends on compatibility and artifact availability. A reproducible deployment also needs controlled dependency inputs and appropriate artifact verification.
Python data and style
Indentation defines code blocks. PEP 8 recommends four spaces per indentation level, snake_case for functions and variables, UPPER_CASE for constants and CapWords for classes. Keep the repository’s established conventions in view.
| Type | Example and use |
|---|---|
bool | True or False for a condition. |
int | 8080 for a port; Python integers have arbitrary precision subject to available resources. |
float | 1.75 for load average; ordinary floats use binary approximation for many decimal fractions. |
str | "web01" for Unicode text; f-strings interpolate values. |
list | ["web01", "web02"] is an ordered, mutable sequence. |
tuple | ("web01", 443) is an immutable sequence; a mutable value inside it can still change. |
dict | {"host": "web01", "port": 443} maps unique hashable keys to values. Modern Python preserves insertion order. |
set | {"web", "proxy"} represents distinct members without a promised iteration order. |
A dictionary’s get method returns the stored value when the key is present, including None if that is the value. A missing key returns the specified default or None when the default is omitted.
server_meta = {"hostname": "web01", "roles": ["web"], "active": True}
datacenter = server_meta.get("datacenter", "unknown")
print(f"{server_meta['hostname']} is in {datacenter}")
Built-in functions such as len and types such as dict are ready to use. Import standard-library modules for additional facilities. Your own modules can group related definitions, and packages organize modules under a shared import name. Third-party distribution packages installed with pip can provide importable modules, but their distribution and import names can differ.
Standard-library tools and external commands
| Module | Linux administration task |
|---|---|
sys | Read sys.argv, write diagnostics to sys.stderr, and use sys.exit to raise SystemExit for the caller’s status. |
os | Read environment variables with os.environ and use OS interfaces such as directory or permissions operations. |
pathlib | Join paths with / and read text with an explicit encoding. Handle OSError when actually accessing a path. |
json | Use loads and dumps on in-memory values or load and dump with file objects. A decoded JSON value can be a list, scalar, or object; check the expected structure. |
shutil | Use disk_usage for byte totals and which to look up a command. copy2 attempts to preserve supported metadata and does not guarantee ownership or a complete backup. |
subprocess | Launch a command and read its exit status and streams. |
For the following Linux diagnostic, assume /usr/bin/df is the trusted GNU executable, mount_path is an approved absolute path and output is UTF-8:
import subprocess
result = subprocess.run(
["/usr/bin/df", "-h", "--", mount_path],
capture_output=True,
encoding="utf-8",
check=True,
timeout=5,
)
print(result.stdout, end="")
The argument list keeps the path in a single argument with the default shell=False. The callee still parses its own arguments. Use a trusted executable, validate the input and use -- where the utility supports it. capture_output=True collects stdout and stderr. The explicit encoding enables text decoding with UTF-8. text=True alone uses the text layer’s default encoding, which can depend on the runtime and locale. check=True raises CalledProcessError for nonzero return codes, including signal termination represented by a negative return code on POSIX. Shell conventions such as 128 plus the signal number are separate. Launch errors can raise OSError, and a timeout can raise TimeoutExpired. Allow expected statuses when an external command uses them to communicate normal outcomes.
A tool such as systemctl is-active --quiet SERVICE reports whether a service meets systemd’s active-state test. To diagnose a nonzero outcome, inspect the targeted unit, systemd availability and detailed status. Configure known units for the platform. Use a separate service health check for application readiness.
Worked example — structured storage report
This lab script reports filesystem figures in bytes for a supplied directory. It uses the filesystem’s reported used and total bytes for the percentage. That calculation need not match the df Use% convention with reserved blocks. A usage failure and a threshold decision remain separate concerns.
#!/usr/bin/env python3
import json
import shutil
import sys
from pathlib import Path
def main():
if len(sys.argv) != 2:
print("Usage: disk_report.py DIRECTORY", file=sys.stderr)
return 2
path = Path(sys.argv[1])
try:
if not path.is_dir():
raise NotADirectoryError(path)
usage = shutil.disk_usage(path)
except OSError as error:
print(f"Storage report failed for {path}: {error}", file=sys.stderr)
return 1
report = {
"directory": str(path),
"total_bytes": usage.total,
"used_bytes": usage.used,
"free_bytes": usage.free,
"used_percent_of_total": (
round(100 * usage.used / usage.total, 1) if usage.total else None
),
}
print(json.dumps(report))
return 0
if __name__ == "__main__":
sys.exit(main())
Run it for an existing lab directory and confirm the result is a JSON object. A missing directory should produce a nonzero status and a diagnostic on stderr, with no success object on stdout. Later automation can enforce a capacity threshold by checking the named metric. Use try and targeted except clauses at the relevant boundary. An optional else runs after the try block completes normally, and finally can release resources when leaving the statement. For files, a with block closes the handle on normal or exceptional exit.
On a Debian 12 lab system, the packaged Python 3.11 is marked externally managed. venv and its pip support are installed. You need a third-party dependency for a project and can write its directory. Which approach installs the dependency while keeping it out of the system interpreter’s global packages?
python3 -m venv .venv, then .venv/bin/python -m pip install -r requirements.txt
Delete the distribution’s EXTERNALLY-MANAGED marker and use the system pip.
Use sudo pip install --break-system-packages -r requirements.txt.
Uninstall the packaged Python and replace it with a custom system build.
A Python 3.11 Linux script has a trusted GNU df at /usr/bin/df, approved mount_path data and UTF-8 output. Which snippet uses no shell, passes mount_path as an operand, captures both streams as UTF-8 text, and raises CalledProcessError for nonzero return?
subprocess.call("df -h " + mount_path, shell=True)
subprocess.run(["/usr/bin/df", "-h", "--", mount_path], capture_output=True, encoding="utf-8", check=True)
os.system("df -h " + mount_path)
subprocess.run(["/usr/bin/df", "-h", "--", mount_path], capture_output=True)
A decoded server inventory object is a Python dictionary named server_meta. Which expression reads datacenter without mutating the dictionary and returns unknown only when the key is absent?
server_meta["datacenter"]
server_meta.pop("datacenter", "unknown")
server_meta.get("datacenter") or "unknown"
server_meta.get("datacenter", "unknown")
Sections you finish are checked off in the contents.