[ SRE_ARENA ]
SRE PYTHON AUTOMATION

The Automation Toolkit.

Implementation Code: 1. Subprocess (Running Commands)
PYTHON
import subprocess

# Run a simple command
result = subprocess.run(["ls", "-l"], capture_output=True, text=True)
print(result.stdout)

# Checking if a command failed
res = subprocess.run(["ping", "-c", "1", "10.0.0.1"], capture_output=True)
if res.returncode != 0:
    print("Host is down!")

# Passing input to a command
subprocess.run(["grep", "ERROR"], input="OK\nERROR\nOK", text=True)
DOWNLOADING CONCEPT: 1. SUBPROCESS (RUNNING COMMANDS)...
  • ↳In SRE, you constantly need to run Linux commands (like kubectl, docker, or grep) from within your Python scripts.
  • ↳The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.
  • ↳Avoid using os.system(), as it's deprecated and insecure.
  • ↳Instead, use subprocess.run().
  • ↳By passing capture_output=True and text=True, you can save the command's output into a Python variable for parsing: result = subprocess.run(['df', '-h'], capture_output=True, text=True) print(result.stdout)
▲ LIVE INCIDENTYou want to check if a website is up, and trigger a PagerDuty alert if it's down.
sre@arena:~/python-sre
sre@arena:~$ python -c "import requests; res = requests.get('https://example.com'); print(res.status_code)"