Python for DevOps — 20 Real Automation Projects (With Line-by-Line
Explanations)
This handbook contains practical DevOps Python scripts with step-by-step explanations. Designed for cloud
engineers & DevOps learners.
1. Server Health Monitor
Monitors CPU, RAM and Disk load.
import psutil
cpu = psutil.cpu_percent()
mem = psutil.virtual_memory().percent
disk = psutil.disk_usage('/').percent
print(f"CPU: {cpu}% MEMORY: {mem}% DISK: {disk}%")
if cpu > 80:
print("High CPU alert!")
Line-by-Line Explanation
import psutil — loads the system monitoring library cpu = ... — gets current CPU usage mem = ... — gets memory
usage percentage disk = ... — gets disk usage percentage print(...) — prints everything in one line if cpu > 80 —
checks alert condition print(...) — prints warning message
2. Log Analyzer
Prints only ERROR lines from logs.
log_file = "[Link]"
with open(log_file) as f:
for line in f:
if "ERROR" in line:
print([Link]())
Line-by-Line Explanation
log_file — defines log file name with open(...) — opens file safely for line — loops through each line if 'ERROR' —
checks condition print(...) — prints clean line
3. API Caller — GitHub
Fetches repository info.
import requests
url = "[Link]
data = [Link](url).json()
print("Repo:", data["name"])
print("Stars:", data["stargazers_count"])
Line-by-Line Explanation
import requests — enables API calls url — GitHub API endpoint [Link] — fetches data .json() — converts to
dictionary print — displays key values
4. Auto Backup Script
Creates zip backup.
import shutil
shutil.make_archive("backup","zip","myfolder")
print("Backup Done")
Line-by-Line Explanation
This script imports required modules, performs the operation, then prints the output.
5. GCP Storage Upload
Uploads file to bucket.
from [Link] import storage
client = [Link]()
bucket = [Link]("my-bucket")
blob = [Link]("[Link]")
blob.upload_from_filename("[Link]")
print("File uploaded")
Line-by-Line Explanation
This script imports required modules, performs the operation, then prints the output.
6. Slack CI/CD Notifier
Sends message.
import requests
[Link]("[Link] Success"})
Line-by-Line Explanation
This script imports required modules, performs the operation, then prints the output.
7. Email Alert
Sends email.
import smtplib
server = [Link]('[Link]',587)
[Link]()
[Link]('you@[Link]','password')
[Link]('you@[Link]','admin@[Link]',"Alert!")
print("Email sent")
Line-by-Line Explanation
This script imports required modules, performs the operation, then prints the output.
8. GCP VM Control
Start VM.
from [Link] import compute_v1
instances = compute_v1.InstancesClient()
[Link](project="my-project",zone="us-central1-a",instance="test-vm")
Line-by-Line Explanation
This script imports required modules, performs the operation, then prints the output.
9. Config Generator
Writes config file.
config={"service":"web","port":8080}
with open("[Link]","w") as f:
for k,v in [Link]():
[Link](f"{k}={v}\n")
Line-by-Line Explanation
This script imports required modules, performs the operation, then prints the output.
10. Deployment Helper
Runs deploy commands.
import os
for cmd in ["git pull","docker build -t app .","docker compose up -d"]:
[Link](cmd)
Line-by-Line Explanation
This script imports required modules, performs the operation, then prints the output.
11. Log Rotation
Archives logs.
import shutil,datetime
log="[Link]"
ts=[Link]().strftime("%Y%m%d")
[Link](log,f"app_{ts}.log")
open(log,"w").close()
Line-by-Line Explanation
This script imports required modules, performs the operation, then prints the output.
12. Disk Alert
Warns low disk.
import psutil
disk=psutil.disk_usage('/').percent
if disk>80: print("Alert!")
Line-by-Line Explanation
This script imports required modules, performs the operation, then prints the output.
13. Kubernetes Pod Checker
Checks pods.
import os
[Link]("kubectl get pods -o wide")
Line-by-Line Explanation
This script imports required modules, performs the operation, then prints the output.
14. Service Check
Tests URL.
import requests
res=[Link]("[Link]
print("UP" if res.status_code==200 else "DOWN")
Line-by-Line Explanation
This script imports required modules, performs the operation, then prints the output.
15. SSH Executor
Runs remote commands.
import paramiko
ssh=[Link]()
ssh.set_missing_host_key_policy([Link]())
[Link]("server",username="user",password="pass")
print(ssh.exec_command("uptime")[1].read().decode())
[Link]()
Line-by-Line Explanation
This script imports required modules, performs the operation, then prints the output.
16. Docker Cleanup
Removes unused.
import os
[Link]("docker system prune -f")
Line-by-Line Explanation
This script imports required modules, performs the operation, then prints the output.
17. Version Generator
Makes version.
version=5
version+=1
print(f"Build-{version}")
Line-by-Line Explanation
This script imports required modules, performs the operation, then prints the output.
18. Daily Job Runner
Runs job daily.
import schedule,time
[Link]().[Link]("10:00").do(lambda: print("Run"))
while True: schedule.run_pending();[Link](1)
Line-by-Line Explanation
This script imports required modules, performs the operation, then prints the output.
19. Slack Bot
Sends message.
import requests
[Link]("[Link] Completed"})
Line-by-Line Explanation
This script imports required modules, performs the operation, then prints the output.
20. YAML Config Reader
Reads yaml.
import yaml
print(yaml.safe_load(open("[Link]")))
Line-by-Line Explanation
This script imports required modules, performs the operation, then prints the output.
Frequently-Used Python Code Snippets (Interview-Ready Cheat Sheet)
These are short, common Python patterns interviewers expect you to know — explained simply and
grouped by topic
1. Print & Variables
Purpose Code Meaning
Print text python\nprint(\"Hello\")\n Output to screen
Create variables python\nname = \"DevOps\"\nage = 25\n Store data
String formatting python\nprint(f\"Name: {name}\")\n f-string formatting
� 2. Data Types
Type Example Usage
String python\ntext = \"hello\"\n Text
Integer python\nnum = 10\n Numbers
Float python\nrate = 3.14\n Decimals
Boolean python\nflag = True\n True / False
� 3. Lists (Very Important)
Task Code
Create list python\nnums = [1, 2, 3]\n
Add item python\[Link](4)\n
Loop list python\nfor n in nums:\n print(n)\n
� 4. Dictionaries (Key-Value Data)
Task Code
Create python\nuser = {\"name\":\"Raj\", \"age\":25}\n
Access python\nprint(user[\"name\"])\n
Loop python\nfor k,v in [Link]():\n print(k,v)\n
� 5. Conditions (if-else)
Task Code
Check value python\nif age >= 18:\n print(\"Adult\")\nelse:\n print(\"Minor\")\n
� 6. Loops
Task Code
For loop python\nfor i in range(5):\n print(i)\n
While loop python\nx = 3\nwhile x>0:\n x-=1\n
� 7. Functions
Task Code
Define function python\ndef greet(name):\n print(\"Hello\", name)\n
Call function python\ngreet(\"Rahul\")\n
8. File Handling (Very Common in DevOps)
Task Code
Write file python\nwith open(\"[Link]\",\"w\") as f:\n [Link](\"hello\")\n
Read file python\nwith open(\"[Link]\") as f:\n print([Link]())\n
9. Exception Handling
Task Code
Prevent crash python\ntry:\n x = 10/0\nexcept Exception as e:\n print(e)\n
10. Working With JSON
Task Code
Parse JSON python\nimport json\nj = '{\"a\":10}'\ndata = [Link](j)\n
11. Import & Modules
Task Code
Import module python\nimport os\n
Use module python\[Link](\"ls\")\n
12. Virtual Environment
Task Command
Create env python -m venv venv
Activate Windows → venv\\Scripts\\activate
Install pkg pip install requests
13. API Calls (Must Know)
import requests
res = [Link]("[Link]
print(res.status_code)
14. Logging (Professional Practice)
import logging
[Link]("Something happened")
15. List Comprehension (Frequently Asked)
nums = [x*x for x in range(5)]