Python is the backbone of DevOps automation β from scripting, monitoring, and configuration management to deploying applications. Today, we explore advanced Python concepts and practical challenges in DevOps!
β‘ Quick Reference
Keep the momentum going β everything you need on LearnXOps in one place:
- π Courses β Video courses & AI-built courses
- π Ebooks β Community ebooks & your own
- π§ͺ All Labs & Challenges β DevOps, Cloud, SRE & more
- βΈοΈ Kubernetes Labs & Playground β kind clusters, playground & challenges
- π€ AI Agent & Bot Labs β OpenClaw Β· Hermes Β· CrewAI Β· LangGraph Β· MCP
Learning points:
πΉ Object-Oriented Programming (OOP) β Classes, Inheritance, and Polymorphism.
πΉ Concurrency & Parallelism β Using threading and multiprocessing.
πΉ Creating & Interacting with APIs β Building REST APIs with FastAPI.
πΉ Database Integration β Working with MySQL/PostgreSQL using SQLAlchemy.
πΉ Logging & Debugging β Setting up structured logging (logging module).
πΉ Infrastructure Automation β Using Python for provisioning servers, managing SSH connections (paramiko).
πΉ Building Python Apps β Flask/Django for web apps
πΉ Packaging & Distribution β Creating Python packages with setuptools.
π§ Learn here:
Python Advance
Object-Oriented Programming (OOP) β Classes, Inheritance, and Polymorphism
What is OOP?
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data (attributes) and code (methods). OOP helps structure complex programs, promotes reusability, and enhances maintainability.
1. Classes
A class is a blueprint for creating objects. It defines a set of attributes and methods that the created objects (instances) will have.
Example:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound"
# Creating an instance
dog = Animal("Dog")
print(dog.speak()) # Output: Dog makes a sound
2. Inheritance
Inheritance allows a class (child class) to inherit attributes and methods from another class (parent class), enabling code reuse and the creation of hierarchical relationships.
Example:
class Dog(Animal):
def speak(self):
return f"{self.name} barks"
# Creating an instance of Dog
dog = Dog("Buddy")
print(dog.speak()) # Output: Buddy barks
3. Polymorphism
Polymorphism allows different classes to define methods with the same name, enabling them to be used interchangeably through a common interface.
Example:
class Cat(Animal):
def speak(self):
return f"{self.name} meows"
animals = [Dog("Rex"), Cat("Whiskers")]
for animal in animals:
print(animal.speak())
# Output:
# Rex barks
# Whiskers meows
Key Benefits of OOP
- Encapsulation: Bundles data and methods within objects.
- Abstraction: Hides internal complexity and shows only necessary details.
- Inheritance: Enables reusability and hierarchy.
- Polymorphism: Promotes flexibility and integration of interchangeable objects.
OOP is widely used in real-world applications such as GUI applications, web development, game development, and system modeling.
Concurrency & Parallelism in Python
Python supports two primary approaches to run multiple tasks simultaneously:
What is Concurrency?
Concurrency is the ability to run multiple tasks seemingly at the same time (interleaved execution), typically using a single core. This is best for I/O-bound operations.
Use Cases for Concurrency
- Handling multiple client requests (e.g., web servers)
- Performing I/O operations (file/network reads/writes)
- Managing long waiting tasks (e.g., API calls, DB operations)
Example: Concurrency using threading
import threading
import time
def print_numbers():
for i in range(5):
print(f"Thread {threading.current_thread().name} - Number: {i}")
time.sleep(1)
# Create two threads
thread1 = threading.Thread(target=print_numbers, name="T1")
thread2 = threading.Thread(target=print_numbers, name="T2")
# Start threads
thread1.start()
thread2.start()
# Wait for threads to complete
thread1.join()
thread2.join()
print("Finished with threading")
β οΈ Threads share memory and are subject to Python's Global Interpreter Lock (GIL).
What is Parallelism?
Parallelism means executing multiple tasks at exactly the same time, usually on different CPU cores. Best suited for CPU-bound tasks.
Use Cases for Parallelism
- CPU-intensive computations (e.g., image processing)
- Data crunching and transformation
- Training ML models
Example: Parallelism using multiprocessing
import multiprocessing
import time
def print_numbers():
for i in range(5):
print(f"Process {multiprocessing.current_process().name} - Number: {i}")
time.sleep(1)
# The guard is required: on macOS and Windows each child process re-imports
# this file, and without it every child would start new processes too.
if __name__ == "__main__":
# Create two processes
process1 = multiprocessing.Process(target=print_numbers, name="P1")
process2 = multiprocessing.Process(target=print_numbers, name="P2")
# Start processes
process1.start()
process2.start()
# Wait for processes to complete
process1.join()
process2.join()
print("Finished with multiprocessing")β Processes run in separate memory space and avoid GIL issues.
Threading vs Multiprocessing
| Feature | Threading (Concurrency) | Multiprocessing (Parallelism) |
|---|---|---|
| Memory | Shared | Separate |
| GIL Affected | Yes | No |
| Type | Concurrency | Parallelism |
| Ideal For | I/O-bound tasks | CPU-bound tasks |
| Examples | Web Scraping, API calls | Video encoding, ML training |
Creating & Interacting with APIs β Building REST API with FastAPI
What is FastAPI?
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python, based on standard Python type hints.
π‘ Why FastAPI?
- Fast: Built on Starlette and Pydantic β one of the fastest Python frameworks.
- Easy to Use: Minimal code with automatic docs generation.
- Type Safe: Leverages type hints for validation.
- Async Support: First-class support for async/await.
π¦ Installation
pip install fastapi uvicorn
Basic FastAPI Example
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Welcome to FastAPI!"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "query": q}
Running the API Server
uvicorn main:app --reload
--reload is useful during development β auto-reloads when you make changes.Auto-Generated Documentation
- Swagger UI: http://127.0.0.1:8000/docs
- ReDoc: http://127.0.0.1:8000/redoc
Interacting with the API (Example with curl)
curl http://127.0.0.1:8000/
curl "http://127.0.0.1:8000/items/42?q=fastapi"
FastAPI CRUD Example with Async SQLAlchemy
A FastAPI CRUD boilerplate built on SQLAlchemy 2.0's async engine and sessions. It works with PostgreSQL, MySQL or SQLite: change the database URL and install the matching async driver. (The older version of this example used the databases package, which has gone quiet and needed an extra sync driver just to create tables.)
π Project Structure
.
βββ main.py
βββ models.py
βββ schemas.py
βββ crud.py
βββ database.py
βββ requirements.txt
requirements.txt
fastapi
uvicorn[standard]
sqlalchemy>=2.0
pydantic>=2
asyncpg # PostgreSQL driver (aiomysql for MySQL, aiosqlite for SQLite) database.py
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase
DATABASE_URL = "postgresql+asyncpg://user:password@localhost:5432/mydb"
engine = create_async_engine(DATABASE_URL)
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
class Base(DeclarativeBase):
pass
async def get_session():
"""FastAPI dependency: one session per request."""
async with SessionLocal() as session:
yield session models.py
from sqlalchemy import String
from sqlalchemy.orm import Mapped, mapped_column
from database import Base
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(50))
email: Mapped[str] = mapped_column(String(100), unique=True) schemas.py
from pydantic import BaseModel, ConfigDict
class UserIn(BaseModel):
name: str
email: str
class UserOut(UserIn):
model_config = ConfigDict(from_attributes=True) # build from SQLAlchemy objects
id: int crud.py
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from models import User
from schemas import UserIn
async def create_user(session: AsyncSession, data: UserIn) -> User:
user = User(**data.model_dump())
session.add(user)
await session.commit()
await session.refresh(user)
return user
async def get_user(session: AsyncSession, user_id: int) -> User | None:
return await session.get(User, user_id)
async def get_all_users(session: AsyncSession) -> list[User]:
result = await session.scalars(select(User).order_by(User.id))
return list(result)
async def update_user(session: AsyncSession, user_id: int, data: UserIn) -> User | None:
user = await session.get(User, user_id)
if user is None:
return None
user.name, user.email = data.name, data.email
await session.commit()
return user
async def delete_user(session: AsyncSession, user_id: int) -> bool:
user = await session.get(User, user_id)
if user is None:
return False
await session.delete(user)
await session.commit()
return True main.py
from contextlib import asynccontextmanager
from fastapi import Depends, FastAPI, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
import crud
from database import Base, engine, get_session
from schemas import UserIn, UserOut
@asynccontextmanager
async def lifespan(app: FastAPI):
# creates tables on startup for the demo; use Alembic migrations in production
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
yield
await engine.dispose()
app = FastAPI(lifespan=lifespan)
@app.post("/users/", response_model=UserOut, status_code=201)
async def create(user: UserIn, session: AsyncSession = Depends(get_session)):
return await crud.create_user(session, user)
@app.get("/users/{user_id}", response_model=UserOut)
async def read(user_id: int, session: AsyncSession = Depends(get_session)):
user = await crud.get_user(session, user_id)
if user is None:
raise HTTPException(status_code=404, detail="User not found")
return user
@app.get("/users/", response_model=list[UserOut])
async def read_all(session: AsyncSession = Depends(get_session)):
return await crud.get_all_users(session)
@app.put("/users/{user_id}", response_model=UserOut)
async def update(user_id: int, user: UserIn, session: AsyncSession = Depends(get_session)):
updated = await crud.update_user(session, user_id, user)
if updated is None:
raise HTTPException(status_code=404, detail="User not found")
return updated
@app.delete("/users/{user_id}")
async def delete(user_id: int, session: AsyncSession = Depends(get_session)):
if not await crud.delete_user(session, user_id):
raise HTTPException(status_code=404, detail="User not found")
return {"message": "User deleted"}Switching Between SQL Databases
Modify the DATABASE_URL in database.py:
SQLite:
sqlite+aiosqlite:///./test.db
MySQL:
mysql+aiomysql://user:password@localhost:3306/dbname
PostgreSQL:
postgresql+asyncpg://user:password@localhost:5432/dbname
Run the App
uvicorn main:app --reload
Python Logging & Debugging β Structured Logging with logging Module
What is Logging?
Logging is the process of recording events, errors, and informational messages during the execution of a program. It helps:
- Debug and trace issues
- Monitor application behavior
- Maintain logs for auditing
Why Use the logging Module?
- It's built-in and easy to configure.
- Supports log levels, formatting, and file output.
- Enables structured and centralized logging.
- Better alternative to using
print()in production.
Basic Logging Setup
import logging
# Basic config
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s"
)
logger = logging.getLogger("AppLogger")
logger.debug("This is a DEBUG message.")
logger.info("This is an INFO message.")
logger.warning("This is a WARNING message.")
logger.error("This is an ERROR message.")
logger.critical("This is a CRITICAL message.")
Writing Logs to a File
logging.basicConfig(
filename='app.log',
level=logging.DEBUG,
format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
filemode='w'
)
logger = logging.getLogger("FileLogger")
logger.info("Logging to a file now.")
Structured Logging with Handlers & Formatters
logger = logging.getLogger("StructuredLogger")
logger.setLevel(logging.DEBUG)
# Console handler
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.WARNING)
# File handler
file_handler = logging.FileHandler("structured.log")
file_handler.setLevel(logging.DEBUG)
# Formatter
formatter = logging.Formatter('%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s')
console_handler.setFormatter(formatter)
file_handler.setFormatter(formatter)
# Add handlers to logger
logger.addHandler(console_handler)
logger.addHandler(file_handler)
# Test log
logger.debug("Debug message with structure")
logger.error("Something went wrong")
Logging Levels
| Level | Description |
|---|---|
| DEBUG | Detailed info, useful for debugging |
| INFO | General info about app operation |
| WARNING | Something unexpected or deprecated |
| ERROR | A more serious problem |
| CRITICAL | Critical error, program may stop |
Real-Life Use Case Example
def divide(x, y):
logger = logging.getLogger("Calculator")
try:
result = x / y
logger.info(f"Division result: {result}")
return result
except ZeroDivisionError:
logger.exception("Division by zero error")
return None
divide(10, 2)
divide(5, 0)
Infrastructure Automation β Using Python for Provisioning Servers & Managing SSH (Paramiko)
What is Infrastructure Automation?
Infrastructure automation is the process of automatically provisioning and managing infrastructure (servers, networks, VMs, containers) using scripts and toolsβremoving the need for manual, error-prone operations.
Why use Python?
- Python is easy to write and read.
- Large ecosystem of libraries (e.g.,
paramiko,fabric,boto3). - Ideal for writing custom infrastructure workflows.
- Cross-platform and widely supported in DevOps tools.
SSH Automation with paramiko
Use Case:
- Log in to remote Linux servers
- Run commands
- Transfer files
- Automate server setup scripts
π§± Installing Paramiko
pip install paramiko
Example: Running Commands via SSH
import paramiko
# Create SSH client
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Connect to remote server
ssh.connect(hostname='your.server.ip', username='ubuntu', key_filename='/path/to/private/key.pem')
# Execute command
stdin, stdout, stderr = ssh.exec_command('uname -a')
print(stdout.read().decode())
# Close connection
ssh.close()
π Example: Uploading a File
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('your.server.ip', username='ubuntu', key_filename='/path/to/private/key.pem')
# SFTP is built into paramiko, no extra package needed
with ssh.open_sftp() as sftp:
sftp.put('localfile.txt', '/home/ubuntu/remote.txt')
ssh.close()Provisioning Servers with Python
While actual server provisioning (creating VMs/instances) is usually done via tools like Terraform or cloud SDKs, you can use Python + cloud SDKs like boto3 (for AWS), google-cloud-compute, or azure-mgmt.
βοΈ Example: Launch EC2 Instance with boto3
import boto3
ec2 = boto3.resource('ec2', region_name='us-east-1')
# Launch instance
instances = ec2.create_instances(
ImageId='ami-0abcdef1234567890',
MinCount=1,
MaxCount=1,
InstanceType='t3.micro',
KeyName='your-keypair-name'
)
for instance in instances:
print(f"Launched EC2: {instance.id}")
Real-World Use Cases
| Use Case | Tool/Library |
|---|---|
| Remote command execution | paramiko |
| File transfers over SSH | paramiko, scp |
| AWS server provisioning | boto3 |
| Setup Docker/Nginx/MySQL remotely | Bash + paramiko |
| Automated backups | fabric, cron |
Building Python Apps β Flask/Django for Web Applications
Flask and Django are two of the most popular Python web frameworks.
- Flask is lightweight, micro, and flexible β ideal for small to medium apps.
- Django is full-featured and includes everything needed for large-scale web development.Why Use Flask or Django?
| Framework | Best For | Features |
|---|---|---|
| Flask | Microservices, APIs | Lightweight, Minimal, Easy to Extend |
| Django | Full Web Apps, Admin Panels | Batteries-included, ORM, Auth, Admin |
Use Cases
- Flask: REST APIs, microservices, prototypes
- Django: eCommerce platforms, CMS, dashboards, large-scale apps
Flask Example β Simple REST API
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/")
def home():
return jsonify(message="Hello from Flask!")
if __name__ == "__main__":
app.run(debug=True)
Run Flask App:
export FLASK_APP=app.py
flask run
Django Example β Basic Project Setup
1οΈβ£ Create a Django Project
pip install django
django-admin startproject mysite
cd mysite
python manage.py runserver
2οΈβ£ Create an App and View
python manage.py startapp hello
Edit hello/views.py:
from django.http import HttpResponse
def greet(request):
return HttpResponse("Hello from Django!")
Configure in urls.py:
from django.urls import path
from hello.views import greet
urlpatterns = [
path('', greet),
]
Flask vs Django
| Feature | Flask | Django |
|---|---|---|
| Type | Microframework | Full-stack framework |
| Flexibility | High | Convention over configuration |
| Built-in Admin | β No | β Yes |
| ORM | Optional (SQLAlchemy) | Built-in (Django ORM) |
| Ideal For | APIs, Prototypes | Full-featured Web Apps |
π§ Tips
- Use Flask when you want more control over components.
- Use Django when you want speed and structure for building complex applications.
Packaging & Distribution β Creating Python Packages with setuptools
Packaging your Python code allows you to share and reuse it via tools like pip. The setuptools library is the most widely-used tool to create Python packages and publish them to PyPI.
Why Package Python Code?
- Reusability across projects.
- Easy distribution via PyPI or private indexes.
- Version management and dependency control.
π Project Structure Example
my_package/
βββ src/
β βββ my_package/
β βββ __init__.py
β βββ core.py
βββ tests/
β βββ test_core.py
βββ README.md
βββ LICENSE
βββ pyproject.tomlpyproject.toml Example (setuptools backend)
[build-system]
requires = ["setuptools>=77"]
build-backend = "setuptools.build_meta"
[project]
name = "my_package"
version = "0.1.0"
description = "A sample Python package"
readme = "README.md"
license = "MIT"
requires-python = ">=3.9"
authors = [{ name = "Your Name", email = "[email protected]" }]
dependencies = []
classifiers = [
"Programming Language :: Python :: 3",
"Operating System :: OS Independent",
]
[project.urls]
Homepage = "https://github.com/yourusername/my_package"Building the Package
# setup.py sdist bdist_wheel is deprecated; build from pyproject.toml
pip install build
python -m buildOutput will be in the dist/ folder.
Uploading to PyPI (using twine)
pip install twine
twine upload dist/*
You will need a PyPI account and API token.
Installation Test
pip install my_package
π§ Tips
- Use
pyproject.tomlfor modern builds and better compatibility. - Add tests and CI for production packages.
- Follow semantic versioning (semver.org).
ποΈ Resources:
π Concurrency & Parallelism β Python Threading Docs
π Build Flask App β DigitalOcean Flask Guide
Initial Tasks:
β Task 1: Set up a virtual environment (venv) and install the required packages (pip install flask django requests).
π₯ Challenges
πΉ Challenge 1: Create a Python script that connects to a remote server via SSH using paramiko.
πΉ Challenge 2: Build a simple Flask API with an endpoint that returns system health (CPU/memory usage).
πΉ Challenge 3: Create a Django app, set up models, views, and templates for a basic CRUD operation.
πΉ Challenge 4: Use Python subprocess to execute system commands and capture output.
πΉ Challenge 5: Build a Flask API that fetches live weather data from an external API and returns it in JSON format.
πΉ Challenge 6: Deploy a Django application on AWS EC2 with Nginx & Gunicorn.
πΉ Challenge 7: Write a Python program to parse log files and extract failed SSH login attempts.
πΉ Challenge 8: Use fabric or paramiko to automate SSH login and run commands on multiple servers.
πΉ Challenge 9: Implement a Python script that monitors Docker containers and sends alerts if a container crashes.
πΉ Challenge 10: Write a Python program that checks a GitHub repository for new commits and triggers a build job.
πΉ Challenge 11: Package your Python script as a CLI tool using argparse and click.
πΉ Challenge 12: Use any python binary package builder like PyInstaller, Nuitka, Cython, PyOxidizer etc, so the code is harder to reverse engineer and easy to distribute
β Solutions:
πΉ Challenge 1: SSH to Remote Server Using Paramiko
import paramiko
def ssh_connect(hostname, username=None, password=None, key_path=None, command=None):
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print(f"π Connecting to {hostname}...")
if key_path:
client.connect(hostname, username=username, key_filename=key_path, timeout=10)
else:
client.connect(hostname, username=username, password=password, timeout=10)
print(f"β
Connected to {hostname}")
stdin, stdout, stderr = client.exec_command(command)
print("π Command Output:")
print(stdout.read().decode())
error = stderr.read().decode()
if error:
print(f"β Error:\n{error}")
client.close()
print("π Disconnected.")
except paramiko.AuthenticationException:
print("β Authentication failed. Check your credentials.")
except paramiko.SSHException as e:
print(f"β SSH error: {e}")
except Exception as e:
print(f"β An error occurred: {e}")
auth_method = input("Choose authentication method (1: Username & Password, 2: SSH Key): ")
hostname = input("Enter remote server IP or hostname: ")
if auth_method == "1":
username = input("Enter SSH username: ")
password = input("Enter SSH password: ")
key_path = None
elif auth_method == "2":
username = input("Enter SSH username: ")
key_path = input("Enter path to SSH private key: ")
password = None
else:
print("β Invalid selection. Exiting.")
exit()
command = input("Enter command to execute: ")
ssh_connect(hostname, username, password, key_path, command)
πΉ Challenge 2: System Health API using Flask + psutil
from flask import Flask, jsonify
import psutil
app = Flask(__name__)
@app.route('/health', methods=['GET'])
def system_health():
disk_usage = psutil.disk_usage('/')
net_io = psutil.net_io_counters()
health_data = {
"cpu_usage": psutil.cpu_percent(interval=1),
"memory_usage": psutil.virtual_memory().percent,
"disk_usage": {
"total": disk_usage.total,
"used": disk_usage.used,
"free": disk_usage.free,
"percent": disk_usage.percent
},
"network": {
"bytes_sent": net_io.bytes_sent,
"bytes_received": net_io.bytes_recv,
"packets_sent": net_io.packets_sent,
"packets_received": net_io.packets_recv
}
}
return jsonify(health_data)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000) # never debug=True on 0.0.0.0: the debugger runs arbitrary code
πΉ Challenge 3: Django CRUD App
Step 1: Create the project and app
pip install django
django-admin startproject taskmanager
cd taskmanager
python manage.py startapp tasks
# then add "tasks" to INSTALLED_APPS in taskmanager/settings.pyStep 2: Model
# tasks/models.py
from django.db import models
class Task(models.Model):
title = models.CharField(max_length=200)
description = models.TextField(blank=True)
completed = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.titleStep 3: Views (Django's generic class-based views, so no separate forms.py is needed)
# tasks/views.py: Django's generic views handle the forms and redirects
from django.urls import reverse_lazy
from django.views.generic import CreateView, DeleteView, ListView, UpdateView
from .models import Task
FIELDS = ["title", "description", "completed"]
class TaskListView(ListView): # renders tasks/task_list.html
model = Task
class TaskCreateView(CreateView): # renders tasks/task_form.html
model = Task
fields = FIELDS
success_url = reverse_lazy("task-list")
class TaskUpdateView(UpdateView): # reuses tasks/task_form.html
model = Task
fields = FIELDS
success_url = reverse_lazy("task-list")
class TaskDeleteView(DeleteView): # renders tasks/task_confirm_delete.html
model = Task
success_url = reverse_lazy("task-list")Step 4: URLs
# tasks/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.TaskListView.as_view(), name="task-list"),
path("new/", views.TaskCreateView.as_view(), name="task-create"),
path("<int:pk>/edit/", views.TaskUpdateView.as_view(), name="task-update"),
path("<int:pk>/delete/", views.TaskDeleteView.as_view(), name="task-delete"),
]
# taskmanager/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("tasks.urls")),
]Step 5: Templates in tasks/templates/tasks/
<!-- tasks/templates/tasks/task_list.html -->
<h1>Tasks</h1>
<a href="{% url 'task-create' %}">New task</a>
<ul>
{% for task in object_list %}
<li>
{% if task.completed %}β
{% endif %} {{ task.title }}
<a href="{% url 'task-update' task.pk %}">Edit</a>
<a href="{% url 'task-delete' task.pk %}">Delete</a>
</li>
{% empty %}
<li>No tasks yet.</li>
{% endfor %}
</ul>
<!-- tasks/templates/tasks/task_form.html -->
<h1>{% if object %}Edit{% else %}New{% endif %} task</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
<a href="{% url 'task-list' %}">Back</a>
<!-- tasks/templates/tasks/task_confirm_delete.html -->
<h1>Delete "{{ object.title }}"?</h1>
<form method="post">
{% csrf_token %}
<button type="submit">Yes, delete</button>
</form>
<a href="{% url 'task-list' %}">Cancel</a>Step 6: Migrate and run
python manage.py makemigrations tasks
python manage.py migrate
python manage.py runserver
# open http://127.0.0.1:8000/πΉ Challenge 4: Execute System Commands with Python Subprocess
import shlex
import subprocess
def run_command(command):
try:
# split into an argument list and run it without a shell, so input like
# "ls; rm -rf ~" can't chain extra commands
result = subprocess.run(shlex.split(command), check=True, text=True, capture_output=True)
print("β
Command executed successfully!\n")
print("π Output:\n", result.stdout)
except FileNotFoundError:
print(f"β Command not found: {command.split()[0]}")
except subprocess.CalledProcessError as e:
print(f"β Command failed with exit code {e.returncode}:\n{e.stderr}")
command = input("Enter a system command to run: ")
run_command(command)πΉ Challenge 5: Weather API using Flask + OpenWeatherMap
from flask import Flask, jsonify, request
import requests
app = Flask(__name__)
API_KEY = "your_api_key_here"
BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
@app.route('/weather', methods=['GET'])
def get_weather():
city = request.args.get('city')
if not city:
return jsonify({"error": "β City parameter is required"}), 400
params = {"q": city, "appid": API_KEY, "units": "metric"}
try:
response = requests.get(BASE_URL, params=params, timeout=10)
data = response.json()
if response.status_code != 200:
return jsonify({"error": data.get("message", "Unknown error")}), response.status_code
weather_data = {
"city": data["name"],
"temperature": data["main"]["temp"],
"weather": data["weather"][0]["description"],
"humidity": data["main"]["humidity"],
"wind_speed": data["wind"]["speed"]
}
return jsonify(weather_data)
except requests.exceptions.RequestException as e:
return jsonify({"error": f"API request failed: {e}"}), 500
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000) # never debug=True on 0.0.0.0: the debugger runs arbitrary code
πΉ Challenge 6: Deploy a Django application on AWS EC2 with Nginx & Gunicorn
β Step 1: Launch an AWS EC2 Instance
- Go to the EC2 Dashboard
- Launch a new Ubuntu 24.04 LTS instance (e.g.,
t3.micro) - Configure security group: Allow ports
22 (SSH),80 (HTTP),443 (HTTPS) - Connect via SSH:
ssh -i your-key.pem ubuntu@your-ec2-public-ip
β Step 2: Install Required Packages
sudo apt update && sudo apt upgrade -y
sudo apt install python3-pip python3-venv nginx git -y
β Step 3: Clone Your Django Project
cd /home/ubuntu
git clone https://github.com/your-username/your-django-repo.git django-app
cd django-app
β Step 4: Set Up Virtual Environment & Install Dependencies
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
β Step 5: Configure Django Settings
In settings.py, update:
DEBUG = False
ALLOWED_HOSTS = ["your-ec2-public-ip", "your-domain.com"]
STATIC_ROOT = "/var/www/django-static" # collectstatic copies files here for Nginx to serveCollect static files and run migrations:
sudo mkdir -p /var/www/django-static
sudo chown ubuntu:ubuntu /var/www/django-static
python manage.py collectstatic --noinput
python manage.py migrateβ Step 6: Set Up Gunicorn
pip install gunicorn
# quick test (replace myproject with your project's package name), then Ctrl+C;
# systemd runs it for real in Step 8
gunicorn --workers 3 --bind 127.0.0.1:8000 myproject.wsgi:applicationβ Step 7: Set Up Nginx as Reverse Proxy
Create config file:
sudo nano /etc/nginx/sites-available/django
Paste the following:
server {
listen 80;
server_name your-ec2-public-ip;
location /static/ {
alias /var/www/django-static/;
}
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}Enable the config:
sudo ln -s /etc/nginx/sites-available/django /etc/nginx/sites-enabled
sudo nginx -t
sudo systemctl restart nginx
β Step 8: Run Gunicorn as Background Process
Create a systemd service:
sudo nano /etc/systemd/system/gunicorn.service
Paste the config:
[Unit]
Description=Gunicorn service for Django
After=network.target
[Service]
User=ubuntu
Group=ubuntu
WorkingDirectory=/home/ubuntu/django-app
# same address Nginx proxies to
ExecStart=/home/ubuntu/django-app/venv/bin/gunicorn --workers 3 --bind 127.0.0.1:8000 myproject.wsgi:application
Restart=on-failure
[Install]
WantedBy=multi-user.targetEnable and start the service:
sudo systemctl daemon-reload
sudo systemctl enable --now gunicorn
sudo systemctl status gunicorn --no-pagerβ Step 9: Configure Firewall & Security Groups
sudo ufw allow OpenSSH # allow SSH first, or enabling the firewall locks you out
sudo ufw allow 'Nginx Full'
sudo ufw enableEnsure EC2 security group allows ports 80 and 443.
β Step 10: Access Your App
Visit http://your-ec2-public-ip
Bonus: Enable HTTPS with Let's Encrypt
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d your-domain.com
πΉ Challenge 7: Write a Python program to parse log files and extract failed SSH login attempts
β
Step 1: Create Script parse_ssh_logs.py
import re
LOG_FILE = "/var/log/auth.log" # Modify path if needed
def parse_ssh_failures(log_file):
try:
with open(log_file, "r") as file:
logs = file.readlines()
failed_attempts = []
ssh_fail_pattern = re.compile(r"Failed password for (invalid user )?(\S+) from (\d+\.\d+\.\d+\.\d+) port \d+")
for line in logs:
match = ssh_fail_pattern.search(line)
if match:
user = match.group(2)
ip_address = match.group(3)
failed_attempts.append((user, ip_address))
print("\U0001F4DC Failed SSH Login Attempts:")
for user, ip in failed_attempts:
print(f"\U0001F534 User: {user} | IP: {ip}")
except FileNotFoundError:
print(f"\u274C Error: Log file '{log_file}' not found!")
except Exception as e:
print(f"\u274C An error occurred: {e}")
# Run
parse_ssh_failures(LOG_FILE)
β Step 2: Run the Script
sudo python3 parse_ssh_logs.py
π¨οΈ Example Output
π Failed SSH Login Attempts:
π΄ User: admin | IP: 192.168.1.100
π΄ User: root | IP: 203.0.113.50
π΄ User: test | IP: 178.62.80.100
πΉ Challenge 8: Use Fabric or Paramiko to automate SSH login and run commands on multiple servers
β Option 1: Using Fabric
Fabric simplifies SSH automation with an easy-to-use API.
Step 1: Install Fabric
pip install fabric
Step 2: Create the Python Script fabric_ssh.py
from fabric import Connection
# List of servers to connect to
servers = [
{"host": "192.168.1.100", "user": "ubuntu", "password": "yourpassword", "ssh_key": "/path/to/your/private_key"},
{"host": "192.168.1.101", "user": "ubuntu", "password": "yourpassword", "ssh_key": None},
]
def run_command_on_servers(command):
for server in servers:
try:
print(f"π Connecting to {server['host']}...")
connect_kwargs = {}
if server.get("ssh_key"):
connect_kwargs["key_filename"] = server["ssh_key"]
elif server.get("password"):
connect_kwargs["password"] = server["password"]
conn = Connection(host=server["host"], user=server["user"], connect_kwargs=connect_kwargs)
result = conn.run(command, hide=True)
print(f"β
{server['host']} Output:\n{result.stdout.strip()}\n")
except Exception as e:
print(f"β Failed to connect to {server['host']}: {e}")
# Run a command on all servers
run_command_on_servers("uptime")
Step 3: Run the Script
python fabric_ssh.py
Example Output
π Connecting to 192.168.1.100...
β
192.168.1.100 Output:
10:42:30 up 5 days, 2:30, 2 users, load average: 0.15, 0.12, 0.10
π Connecting to 192.168.1.101...
β
192.168.1.101 Output:
10:42:35 up 7 days, 1:15, 3 users, load average: 0.20, 0.18, 0.12
β Option 2: Using Paramiko
Paramiko provides a low-level interface for SSH operations.
Step 1: Install Paramiko
pip install paramiko
Step 2: Create the Python Script paramiko_ssh.py
import paramiko
# List of servers
servers = [
{"host": "192.168.1.100", "user": "ubuntu", "password": None, "key": "/path/to/private/key"},
{"host": "192.168.1.101", "user": "ubuntu", "password": "yourpassword", "key": None},
]
def run_ssh_command(host, user, password, key, command):
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if key:
client.connect(hostname=host, username=user, key_filename=key, timeout=10)
else:
client.connect(hostname=host, username=user, password=password, timeout=10)
stdin, stdout, stderr = client.exec_command(command)
output = stdout.read().decode().strip()
error = stderr.read().decode().strip()
print(f"β
{host} Output:\n{output}\n" if output else f"β {host} Error:\n{error}\n")
client.close()
except Exception as e:
print(f"β Failed to connect to {host}: {e}")
# Run command on all servers
for server in servers:
print(f"π Connecting to {server['host']}...")
run_ssh_command(server["host"], server["user"], server.get("password"), server.get("key"), "uptime")
Step 3: Run the Script
python paramiko_ssh.py
Example Output
π Connecting to 192.168.1.100...
β
192.168.1.100 Output:
10:42:30 up 5 days, 2:30, 2 users, load average: 0.15, 0.12, 0.10
π Connecting to 192.168.1.101...
β
192.168.1.101 Output:
10:42:35 up 7 days, 1:15, 3 users, load average: 0.20, 0.18, 0.12
πΉ Challenge 9: Monitor Docker containers and alert if any container crashes
β Step 1: Install Required Dependencies
pip install docker
sudo systemctl start docker
β
Step 2: Create the Python Script monitor_docker.py
import docker
import smtplib
import requests
from email.mime.text import MIMEText
client = docker.from_env()
# Email Config (Gmail needs an app password, not your account password)
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587
EMAIL_FROM = "[email protected]"
EMAIL_TO = "[email protected]"
EMAIL_PASSWORD = "your-app-password"
# Slack Config
SLACK_WEBHOOK_URL = "https://hooks.slack.com/services/your/webhook/url"
def send_email_alert(container_name, exit_code):
msg = MIMEText(f"The container '{container_name}' stopped unexpectedly (exit code {exit_code}).")
msg["Subject"] = f"π¨ ALERT: Docker Container {container_name} Stopped!"
msg["From"] = EMAIL_FROM
msg["To"] = EMAIL_TO
try:
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
server.starttls()
server.login(EMAIL_FROM, EMAIL_PASSWORD)
server.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
print(f"π§ Email alert sent for {container_name}")
except Exception as e:
print(f"β Failed to send email: {e}")
def send_slack_alert(container_name, exit_code):
message = {"text": f"π¨ *ALERT:* Docker container `{container_name}` stopped (exit code {exit_code})"}
try:
response = requests.post(SLACK_WEBHOOK_URL, json=message, timeout=10)
response.raise_for_status()
print(f"π¬ Slack alert sent for {container_name}")
except Exception as e:
print(f"β Failed to send Slack alert: {e}")
def monitor_containers():
# Docker emits a "die" event whenever a container's main process exits,
# including containers started after this script, so nothing is missed
print("π Watching Docker events for containers that stop...")
for event in client.events(decode=True, filters={"type": "container", "event": "die"}):
attrs = event["Actor"]["Attributes"]
name, exit_code = attrs.get("name"), attrs.get("exitCode")
print(f"β οΈ {name} stopped (exit code {exit_code})")
send_email_alert(name, exit_code)
send_slack_alert(name, exit_code)
if __name__ == "__main__":
monitor_containers()β Step 3: Run the Script
python monitor_docker.py
β Step 4: Simulate a Container Crash
docker run -d --name test_container alpine sleep 100
docker stop test_container
π¨οΈ Example Output
π Watching Docker events for containers that stop...
β οΈ test_container stopped (exit code 137)
π§ Email alert sent for test_container
π¬ Slack alert sent for test_container
πΉ Challenge 10: Write a Python program that checks a GitHub repository for new commits and triggers a build job
β Step 1: Install Required Dependencies
pip install requests
β
Step 2: Create the Python Script check_github_commits.py
import requests
import time
import json
import os
GITHUB_REPO = "owner/repository"
GITHUB_BRANCH = "main"
GITHUB_API_URL = f"https://api.github.com/repos/{GITHUB_REPO}/commits/{GITHUB_BRANCH}"
LAST_COMMIT_FILE = "last_commit.json"
BUILD_TRIGGER_URL = "https://ci.example.com/build"
# unauthenticated API calls are limited to 60 an hour; a token raises that to 5,000
HEADERS = {"Accept": "application/vnd.github+json"}
if os.getenv("GITHUB_TOKEN"):
HEADERS["Authorization"] = f"Bearer {os.environ['GITHUB_TOKEN']}"
def get_latest_commit():
try:
response = requests.get(GITHUB_API_URL, headers=HEADERS, timeout=10)
response.raise_for_status()
commit_data = response.json()
return commit_data["sha"]
except requests.exceptions.RequestException as e:
print(f"β Error fetching latest commit: {e}")
return None
def load_last_commit():
try:
with open(LAST_COMMIT_FILE, "r") as file:
return json.load(file).get("last_commit")
except FileNotFoundError:
return None
def save_last_commit(commit_sha):
with open(LAST_COMMIT_FILE, "w") as file:
json.dump({"last_commit": commit_sha}, file)
def trigger_build(commit_sha):
try:
response = requests.post(BUILD_TRIGGER_URL, json={"commit": commit_sha}, timeout=10)
if response.status_code == 200:
print(f"β
Build triggered successfully for commit: {commit_sha}")
else:
print(f"β οΈ Failed to trigger build. Status Code: {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"β Error triggering build: {e}")
def monitor_github():
print(f"π Monitoring GitHub repository: {GITHUB_REPO}")
while True:
latest_commit = get_latest_commit()
if not latest_commit:
time.sleep(60)
continue
last_commit = load_last_commit()
if latest_commit != last_commit:
print(f"π New commit detected: {latest_commit}")
trigger_build(latest_commit)
save_last_commit(latest_commit)
else:
print("β
No new commits detected.")
time.sleep(60)
monitor_github()
β Step 3: Run the Script
python check_github_commits.py
π¨οΈ Example Output
π Monitoring GitHub repository: owner/repository
β
No new commits detected.
π New commit detected: 1a2b3c4d5e
β
Build triggered successfully for commit: 1a2b3c4d5e
β
No new commits detected.
πΉ Challenge 11: Package your Python script as a CLI tool using argparse and click
β Option 1: Using argparse
Step 1: Create the Python Script cli_tool.py
import argparse
def greet(name, uppercase):
message = f"Hello, {name}!"
if uppercase:
message = message.upper()
print(message)
def main():
parser = argparse.ArgumentParser(description="Simple CLI tool to greet users.")
parser.add_argument("name", type=str, help="Name of the person to greet")
parser.add_argument("-u", "--uppercase", action="store_true", help="Convert the greeting to uppercase")
args = parser.parse_args()
greet(args.name, args.uppercase)
if __name__ == "__main__":
main()
Step 2: Run the CLI Tool
python cli_tool.py Sandip
Output:
Hello, Sandip!
Run with -u flag:
python cli_tool.py Sandip -u
Output:
HELLO, SANDIP!
β Option 2: Using click
Step 1: Install click
pip install click
Step 2: Create the Python Script cli_tool_click.py
import click
@click.command()
@click.argument("name")
@click.option("--uppercase", is_flag=True, help="Convert the greeting to uppercase")
def greet(name, uppercase):
message = f"Hello, {name}!"
if uppercase:
message = message.upper()
click.echo(message)
if __name__ == "__main__":
greet()
Step 3: Run the CLI Tool
python cli_tool_click.py Sandip
Output:
Hello, Sandip!
Run with --uppercase:
python cli_tool_click.py Sandip --uppercase
Output:
HELLO, SANDIP!
π‘ Bonus: Make it a Global CLI Command
Step 1: Create setup.py
from setuptools import setup
setup(
name="greet-cli",
version="1.0",
py_modules=["cli_tool_click"],
install_requires=["click"],
entry_points={
"console_scripts": [
"greet=cli_tool_click:greet",
],
},
)
Step 2: Install the CLI Tool
pip install --editable .
Step 3: Run Globally
greet Sandip --uppercase
Output:
HELLO, SANDIP!
πΉ Challenge 12: Use any Python binary package builder like PyInstaller, Nuitka, Cython, PyOxidizer, etc. so that code will be hard to reverse engineer and become easily distributable
β Option 1: Using PyInstaller (Easy & Popular)
Step 1: Install PyInstaller
pip install pyinstaller
Step 2: Convert Script into an Executable
pyinstaller --onefile cli_tool.py--onefileβ Bundles everything into a single executable--noconsoleβ hides the console window; for GUI apps only, so it is left off for this CLI tool
Step 3: Run the Executable
- Windows:
dist\cli_tool.exe
- Linux/macOS:
./dist/cli_tool
Step 4: About Obfuscation
# PyInstaller 6 removed --key (bytecode encryption). A PyInstaller bundle can be
# unpacked, so use Nuitka or Cython (below) when the code must be harder to reverse.
pyinstaller --versionβ Option 2: Using Nuitka (Compiles to C for Better Obfuscation)
Step 1: Install Nuitka
pip install nuitka
Step 2: Compile the Script
python -m nuitka --onefile cli_tool.py # --onefile implies --standaloneStep 3: Run the Executable
./cli_tool.bin # Linux/macOS
cli_tool.exe # Windows
β Option 3: Using Cython (Converts Python to Compiled C)
Step 1: Install Cython
pip install cython
Step 2: Convert Script to a C File
cython --embed -o cli_tool.c cli_tool.py
Step 3: Compile to Executable
gcc -o cli_tool cli_tool.c $(python3-config --cflags --ldflags --embed)
Step 4: Run the Executable
./cli_tool
β Option 4: PyOxidizer (no longer maintained)
PyOxidizer's last release, 0.24, dates from early 2023, and in 2024 its author said he had de-prioritized the project and its future was uncertain. The config previously shown here also wouldn't build. Use Nuitka (Option 2) for a single compiled binary, or PyInstaller (Option 1) for the simplest bundle.
How to Participate?
β
Complete the tasks and challenges.
β
Document your progress and key takeaways on GitHub ReadMe, Medium, or Hashnode.
β
Share the above in a LinkedIn post tagging me (Sandip Das) and use #60DaysDevOps to engage with the community!
β‘ Quick Reference
Keep the momentum going β everything you need on LearnXOps in one place:
- π Courses β Video courses & AI-built courses
- π Ebooks β Community ebooks & your own
- π§ͺ All Labs & Challenges β DevOps, Cloud, SRE & more
- βΈοΈ Kubernetes Labs & Playground β kind clusters, playground & challenges
- π€ AI Agent & Bot Labs β OpenClaw Β· Hermes Β· CrewAI Β· LangGraph Β· MCP

Member discussion