Automating Tasks with Python
The DevOps payoff — scripting real work: shell commands, files, and web APIs.
Now the payoff. This lesson shows the three things DevOps scripts do constantly: run shell commands, read and write files, and call web APIs — then combines them into a small automation you could actually use.
🎯 Learning Objectives
By the end of this lesson you will:
- Run shell commands from Python with
subprocess - Read and write files safely
- Call a REST API and parse JSON
- Organize logic into reusable functions
Running Shell Commands
The subprocess module lets Python drive the same commands you’d type in Bash — while keeping Python’s logic and error handling:
import subprocess
result = subprocess.run(
["df", "-h", "/"],
capture_output=True,
text=True,
)
print(result.stdout)⚠ Prefer a list of arguments
Pass the command as a list (["df", "-h", "/"]), not one big string with shell=True. Building shell strings from variables invites command-injection bugs — the list form is safer.
Reading and Writing Files
The with block opens a file and closes it automatically, even if an error occurs:
# Write a config file
with open("report.txt", "w") as f:
f.write("Disk check complete\n")
# Read it back
with open("report.txt") as f:
contents = f.read()
print(contents)💡 Always use 'with'
with open(...) guarantees the file is closed for you. Forgetting to close files is a common source of resource leaks in long-running scripts.
Calling a Web API
Most DevOps work talks to APIs (cloud providers, monitoring, chatops). The requests library makes it simple:
pip3 install requestsimport requests
resp = requests.get("https://api.github.com/repos/python/cpython")
resp.raise_for_status() # fail loudly on HTTP errors
data = resp.json() # parse JSON into a dict
print("Stars:", data["stargazers_count"])Functions: Reusable Building Blocks
Wrap logic in functions so it can be named, reused, and tested:
def disk_usage(path="/"):
result = subprocess.run(
["df", "-h", path],
capture_output=True, text=True,
)
return result.stdout
print(disk_usage("/"))Putting It Together: A Mini Health Check
import subprocess
def check(name, command):
result = subprocess.run(command, capture_output=True, text=True)
ok = result.returncode == 0
print(f"[{'OK' if ok else 'FAIL'}] {name}")
return ok
checks = {
"disk": ["df", "-h", "/"],
"uptime": ["uptime"],
"memory": ["free", "-h"],
}
results = [check(name, cmd) for name, cmd in checks.items()]
print(f"\n{sum(results)}/{len(results)} checks passed")This one script combines everything: functions, a dictionary, a loop, subprocess, and f-strings.
🧪 Hands-on Lab
Build a Log Line Counter
- Write a function
count_errors(path)that opens a log file and counts lines containing the word"ERROR". - Return the count and print it with an f-string.
- Bonus: call a public API with
requestsand print one field from the JSON response.
🧠 Knowledge Check
Which module lets a Python script run shell commands like `df` or `uptime`?
Why is `with open(...) as f:` preferred for working with files?
💼 Interview Preparation
How would you approach writing a Python script to automate a repetitive operations task?
Summary
You can now run shell commands, work with files, call APIs, and structure scripts with functions — the real toolkit of Python automation. Next, we scale automation across many servers at once with Ansible… but first, the cloud that Ansible so often manages: AWS.