← Back to Home
⚙️

Automating Tasks with Python

The DevOps payoff — scripting real work: shell commands, files, and web APIs.

15 min read📚DevOps Fundamentals

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:


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:

python
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:

python
# 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:

bash
pip3 install requests
python
import 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"])
bash — 80×24
student@devops:~$python3 stars.py

Functions: Reusable Building Blocks

Wrap logic in functions so it can be named, reused, and tested:

python
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

python
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")
bash — 80×24
student@devops:~$python3 healthcheck.py

This one script combines everything: functions, a dictionary, a loop, subprocess, and f-strings.


🧪 Hands-on Lab

📝

Build a Log Line Counter

  1. Write a function count_errors(path) that opens a log file and counts lines containing the word "ERROR".
  2. Return the count and print it with an f-string.
  3. Bonus: call a public API with requests and print one field from the JSON response.

🧠 Knowledge Check

Knowledge Check

Which module lets a Python script run shell commands like `df` or `uptime`?

Knowledge Check

Why is `with open(...) as f:` preferred for working with files?


💼 Interview Preparation

Interview Q&A

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.

Up Next

Introduction to AWS

You've mastered this lesson. Continue your journey to becoming a DevOps Engineer.

Start Next Lesson