Sitemap

Python for DevOps

9 min readSep 17, 2025

--

Just sample automation questions and answers

  1. Write a Python script to check if a process is running on a Linux system.
import subprocess

def is_process_running(process_name):
try:
output = subprocess.check_output(['pgrep', '-f', process_name])
return True
except subprocess.CalledProcessError:
return False

# Example:
print(is_process_running("nginx")) # True if running

2. List all files in a directory recursively.

import os

def list_files_recursively(directory):
for root, dirs, files in os.walk(directory):
for file in files:
print(os.path.join(root, file))

# Example:
# list_files_recursively("/var/log")

3. Monitor CPU usage using Python.

import psutil 

def cpu_percent()

return psutil.cpu_percent(interval=1)

print(cpu_percent)

4. Check if a port is open on a remote server.

import socket

def check_port(host, port):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.settimeout(2)
result = sock.connect_ex((host, port))
return result == 0

# Example:
# print(check_port("google.com", 80)) # True if port 80 is open

5. Write a Python script to read and parse a log file for “ERROR” lines.

def find_error(file_path):
with open(file_path, 'r') as file
for line in file:
if "ERROR" in line:
print(line.strip())

find_error("/var/log")

6. Automate a system update using subprocess.

import subprocess

def restart_service(service_name):
try:
subprocess.run(["sudo", "systemctl", "restart", service_name], check=True)
print(f"✅ {service_name} restarted successfully!")
except subprocess.CalledProcessError as e:
print(f"❌ Failed to restart {service_name}: {e}")

restart_service("nginx")

7. Write a Python script to send an alert email if disk usage is more than 90%.

#!/usr/bin/env python3
import psutil
import smtplib
from email.mime.text import MIMEText

# Configuration
THRESHOLD = 90 # percentage
DISK = "/" # mount point to monitor
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587
SENDER_EMAIL = "your_email@gmail.com"
SENDER_PASSWORD = "your_password_or_app_password"
RECEIVER_EMAIL = "alert_receiver@gmail.com"

def check_disk_usage():
usage = psutil.disk_usage(DISK)
return usage.percent

def send_alert(usage):
subject = f"⚠️ Disk Usage Alert: {usage}%"
body = f"Disk usage on {DISK} has reached {usage}%, which is above the {THRESHOLD}% threshold."

msg = MIMEText(body)
msg["Subject"] = subject
msg["From"] = SENDER_EMAIL
msg["To"] = RECEIVER_EMAIL

try:
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
server.starttls() # Secure connection
server.login(SENDER_EMAIL, SENDER_PASSWORD)
server.sendmail(SENDER_EMAIL, RECEIVER_EMAIL, msg.as_string())
print("✅ Alert email sent successfully!")
except Exception as e:
print(f"❌ Failed to send email: {e}")

if usage > THRESHOLD:
send_alert(usage)
else:
print("Disk usage is under control ✅")
import shutil
import smtplib

def usage(path='/'):

used, free, total = shutil.disk_usage(path)
throshold = 80


percent_used = (used\total)* 100

if percent_used > throshold:
print('Exceed')
else:
print("Not")

8. Docker Health Check Script in Python.

import docker

def docker_status():
client = docker.fromenv()
for container in client.container.list()
print(container.name , container.status)

docker_status

9. Automate File Transfer to Multiple Servers.

import paramiko 
from scp import SCPClient

def ssh_connect(server, port, user, password):
client = paramiko.SCPClient()
client.load_system_keys
client.set_missing_key_loads(paramiko.AutoAdd())
client.connect(server, port, user, password)

retunr client

servers = ['','']

for server in servers:
ssh = ssh_connect(server, 22, '', '')
scp = SCPClient(get_transport())
scp.put('src','dest')
scp.close()

10. Create a Python script to rotate logs daily and archive old logs.

import os
import shutil
from datetime import datetime

src = ''
dest = ''


for filename in os.listdir(src):
if filename.endswith('.log'):
full_path=os.path. join(src, filename)
time_stamp = datetime.now().strftmp('')
new_file = f"{}, {}

shutil.move(full_path, os.path.join(dest, new_file))

11. Automate Service Restart on Failure.

import subprocess

server = 'nginx'

def check():
while True:
status= subprocess.run([['systemctl','is-active', servers], capture_output=true , text=true)

if status.stdout.strip() != 'active':
subprocess.run(['systemctl','restart', server])
time.sleep(60)

12. Create a script to monitor disk usage and send an alert if usage exceeds 80%.

import shutil

used, total, free= shutil.disk_usage('/')

percent_used = (used/total) * 100

if percent_used > 100:
with smtplib.SMTP('gmail.com') as server:
server.sendmail('','', )

13. Automate Backup of Configuration Files

import tarfile
import paramiko
from scp import SCPClient

config_files = ['', '']

with tarfile.open('configs_backup.tar.gz', 'w:gz') as tar:
for file in config_files:
tar.add(file)



ssh = paramiko.SCPClient()
ssh.load_system_host_keys
ssh.set_missing_key_loads(paramiko.AutoAdd())
ssh.connnect(server, port, '', '')
scp = SCPClient.(ssh.transport())
scp.put('configs_backup.tar.gz', '/backups/configs_backup.tar.gz')
scp.close()

14. Automate Database Health Check

import psycopy2

try:
connect = psycopy2.conn(database= , user= , port= , password= )
cur = connect.cursor()
cur.execute("SELECT 1")
print("Database is healt")

expect Exception as e:
print("Not health")

15. How to parse and update a YAML config file in Python

import yaml 

with open('deployment.yaml', 'r') as file:
data = yaml.safe_load(file)

data['app_port'] = 8080

with open('deployment.yaml', 'w') as file:
yaml.dump(data, file)

16. Automate Cleanup of Temporary Files

import os 
import time


dir = '/tmp'
now = time.time()


for filename in os.listdir(dir):
file_path = os.path.join(dir, filename)
if os.stat(file_path).st_mtime < now - 7 * 864000:
os.remove(file_path)

17. How do you check the status of a Jenkins job using Python?

import request 

url = ""
res = request.get(url, auth=('admin', 'api'))
print(res.status_code)

18. List all EC2 instances in a region

import boto3

ec2 = boto3.client("ec2", region_name="us-east-1")

for res in ec2.describe_instances()["Reservations"]:
for inst in res["Instances"]:
print(inst["InstanceId"], inst["State"]["Name"])

19. Start & Stop an EC2 instance

import boto3

ec2 = boto3.client("ec2", region_name="us-east-1")
instance_id = "i-1234567890abcdef"

# Start
ec2.start_instances(InstanceIds=[instance_id])
print("Started:", instance_id)

# Stop
ec2.stop_instances(InstanceIds=[instance_id])
print("Stopped:", instance_id)

19. Upload a file to S3 bucket

import boto3

s3 = boto3.client("s3")
s3.upload_file("local.txt", "my-bucket", "remote.txt")
print("Uploaded successfully")

20. Insert item into DynamoDB

import boto3

table = boto3.resource("dynamodb").Table("Users")
table.put_item(Item={"id": "101", "name": "Vinod", "role": "DevOps"})
print("Item added")

Python Intermediate level

  1. Take daily backups of all EC2 instances’ EBS volumes.
import boto3
from datetime import datetime

ec2 = boto3.client("ec2", region_name="us-east-1")

for res in ec2.describe_instances()["Reservations"]:
for inst in res["Instances"]:
instance_id = inst["InstanceId"]
for vol in inst["BlockDeviceMappings"]:
vol_id = vol["Ebs"]["VolumeId"]
snap = ec2.create_snapshot(
VolumeId=vol_id,
Description=f"Backup of {vol_id} from {instance_id} at {datetime.utcnow()}"
)
print(f"Created snapshot {snap['SnapshotId']} for volume {vol_id}")

2. Stop EC2s with CPU usage < 5% for last 1 hour.

import boto3
import datetime

cloudwatch = boto3.client("cloudwatch", region_name="us-east-1")
ec2 = boto3.client("ec2", region_name="us-east-1")

for res in ec2.describe_instances()["Reservations"]:
for inst in res["Instances"]:
instance_id = inst["InstanceId"]

metrics = cloudwatch.get_metric_statistics(
Namespace="AWS/EC2",
MetricName="CPUUtilization",
Dimensions=[{"Name": "InstanceId", "Value": instance_id}],
StartTime=datetime.datetime.utcnow() - datetime.timedelta(hours=1),
EndTime=datetime.datetime.utcnow(),
Period=300,
Statistics=["Average"]
)

if metrics["Datapoints"] and metrics["Datapoints"][0]["Average"] < 5:
ec2.stop_instances(InstanceIds=[instance_id])
print(f"Stopped idle instance: {instance_id}")

3. Collect app logs, upload to S3, then notify team.

import boto3

s3 = boto3.client("s3")
sns = boto3.client("sns")

bucket = "my-log-bucket"
file_path = "app.log"
s3_key = "logs/app.log"

# Upload log file
s3.upload_file(file_path, bucket, s3_key)

# Notify via SNS
sns.publish(
TopicArn="arn:aws:sns:us-east-1:123456789012:LogAlerts",
Message=f"New log file uploaded: s3://{bucket}/{s3_key}"
)

print("Log uploaded & notification sent")

4. Write a Python script to list pods in a namespace and restart those in CrashLoopBackOff.

from kubernetes import client, config

def restart_crashloop_pods(namespace="default"):
# Load kubeconfig (works with ~/.kube/config or in-cluster)
config.load_kube_config()

v1 = client.CoreV1Api()
pods = v1.list_namespaced_pod(namespace)

for pod in pods.items:
pod_name = pod.metadata.name

# Check pod status for CrashLoopBackOff
for container_status in pod.status.container_statuses or []:
state = container_status.state
if state.waiting and state.waiting.reason == "CrashLoopBackOff":
print(f"[!] Pod {pod_name} is in CrashLoopBackOff. Restarting...")
# Delete the pod (K8s will recreate it via ReplicaSet/Deployment)
v1.delete_namespaced_pod(name=pod_name, namespace=namespace)
print(f" -> Deleted pod {pod_name}")
break

if __name__ == "__main__":
restart_crashloop_pods("default") # Change namespace if needed

5. Write a Python script that checks if a service is running, restarts it if not, and logs the event.

import subprocess
import logging
from datetime import datetime

# Configure logging
logging.basicConfig(
filename="/var/log/service_monitor.log",
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)

def is_service_active(service_name):
"""Check if the service is active"""
try:
status = subprocess.run(
["systemctl", "is-active", service_name],
capture_output=True,
text=True
)
return status.stdout.strip() == "active"
except Exception as e:
logging.error(f"Error checking service {service_name}: {e}")
return False

def restart_service(service_name):
"""Restart the service"""
try:
subprocess.run(["systemctl", "restart", service_name], check=True)
logging.info(f"Service {service_name} restarted successfully.")
except subprocess.CalledProcessError as e:
logging.error(f"Failed to restart {service_name}: {e}")

def monitor_service(service_name):
"""Monitor and restart service if not running"""
if is_service_active(service_name):
logging.info(f"Service {service_name} is running.")
else:
logging.warning(f"Service {service_name} is not running. Restarting...")
restart_service(service_name)

if __name__ == "__main__":
service = "nginx" # 🔧 Change this to your service name
monitor_service(service)

6. Workload Scheduler For Kubernetes-like cluster.
Each node can hold a maximum of 100 CPU units.
A node is considered safe if its load is ≤ 70 CPU units.
Workloads should be distributed across the minimum number of nodes.
Always try to keep nodes safe first.
If the workload cannot be distributed while keeping all nodes ≤ 70, then nodes may be overloaded (up to 100).

def schedule_workloads(workloads):
"""
Schedule workloads across minimum number of nodes.
Each node:
- max capacity = 100
- safe limit = 70
Strategy:
- First try to keep all nodes <= 70 (safe placement)
- If not possible, allow filling up to 100
"""
nodes = [] # each element is CPU load of a node

# Sort workloads (biggest first for best-fit decreasing strategy)
workloads.sort(reverse=True)

for w in workloads:
placed = False

# First try to place in existing safe nodes
for i in range(len(nodes)):
if nodes[i] + w <= 70:
nodes[i] += w
placed = True
break

# If not placed safely, try to place in nodes but ≤ 100
if not placed:
for i in range(len(nodes)):
if nodes[i] + w <= 100:
nodes[i] += w
placed = True
break

# If still not placed, create a new node
if not placed:
nodes.append(w)

return nodes


# Example
workloads = [30, 20, 50, 40, 60, 25, 10]
result = schedule_workloads(workloads)

print("Final Node Loads:", result)
print("Total Nodes Used:", len(result))

7. Given a pod CPU request in millicores (cpu), recommend an optimized allocation using these rules:

  • cpu < 0 → return 0
  • cpu = 0 → return 250
  • Standard units: [250, 500, 1000, 2000, 4000, 8000]
  • If cpu matches a unit → return it
  • Otherwise → return the nearest higher unit
  • If cpu > 8000 → return 8000
def recommend_cpu(cpu):
units = [250, 500, 1000, 2000, 4000, 8000]

# Rule 1: invalid or negative
if cpu < 0:
return 0

# Rule 2: default minimum
if cpu == 0:
return 250

# Rule 3: cap at max
if cpu > 8000:
return 8000

# Rule 4: find nearest higher or exact
for unit in units:
if cpu <= unit:
return unit

# Examples
print(recommend_cpu(-10)) # 0
print(recommend_cpu(0)) # 250
print(recommend_cpu(300)) # 500
print(recommend_cpu(1000)) # 1000
print(recommend_cpu(2200)) # 4000
print(recommend_cpu(9000)) # 8000

8. In Kubernetes, pods request memory in Mi (Mebibytes).
Given a pod’s requested memory (integer mem in Mi), recommend an allocation from the standard set:

  • Standard units: [128, 256, 512, 1024, 2048, 4096, 8192] (Mi)
  • Rules:
  • If input ≤ 0 → return 128 (minimum).
  • If input matches a unit exactly → return it.
  • Otherwise round up to nearest higher unit
  • If input exceeds 8192, cap at 8192.
def recommend_memory(mem: int) -> int:
units = [128, 256, 512, 1024, 2048, 4096, 8192]

if mem <= 0:
return 128
if mem >= 8192:
return 8192
if mem in units:
return mem

for unit in units:
if mem < unit:
return unit

# Example
print(recommend_memory(0)) # 128
print(recommend_memory(300)) # 512
print(recommend_memory(8192)) # 8192
print(recommend_memory(9000)) # 8192

9. Kubernetes Pod Restart Counter

Get Vinodkhathi’s stories in your inbox

Join Medium for free to get updates from this writer.

You are given a list of pod events (like ["Running", "CrashLoopBackOff", "Running", "Error", "Running"]).
Count how many times the pod restarted.

  • A restart is counted whenever the pod goes from a non-Running state back to Running.
def count_restarts(events):
restarts = 0
for i in range(1, len(events)):
if events[i] == "Running" and events[i-1] != "Running":
restarts += 1
return restarts

# Example
events = ["Running", "CrashLoopBackOff", "Running", "Error", "Running"]
print(count_restarts(events)) # 2

10. Kubernetes Node Disk Usage Alert

Each node has a disk capacity of 100 Gi.
You are given a dictionary of node usages (in Gi), e.g.:

{"node1": 60, "node2": 85, "node3": 95}

Raise alerts:

If usage > 90 → “Critical”

If usage > 70 → “Warning”

Else “Healthy”

def disk_alerts(usage_dict):
alerts = {}
for node, usage in usage_dict.items():
if usage > 90:
alerts[node] = "Critical"
elif usage > 70:
alerts[node] = "Warning"
else:
alerts[node] = "Healthy"
return alerts

# Example
nodes = {"node1": 60, "node2": 85, "node3": 95}
print(disk_alerts(nodes))
# {'node1': 'Healthy', 'node2': 'Warning', 'node3': 'Critical'}

Python Basic

  1. Reverse a string in Python
s = "hello"
print(s[::-1]) # olleh

# Without slicing
rev = "".join(reversed(s))
print(rev)

2. Find the first non-repeated character in a string.

s = "aabbccdeff"
for ch in s:
if s.count(ch) == 1:
print(ch) # d
break

3. Find duplicates in a list.

nums = [1, 2, 3, 2, 4, 1, 5]
duplicates = [x for x in set(nums) if nums.count(x) > 1]
print(duplicates) # [1, 2]




# OR


def find_duplicates(input_list):
seen = set()
duplicates = set()

for item in input_list:
if item in seen:
duplicates.add(item)
else:
seen.add(item)

return list(duplicates)


# Example usage
my_list = [1, 2, 3, 4, 2, 5, 6, 3, 7, 8, 1]
print("Duplicates:", find_duplicates(my_list))

4. Count vowels in a string.

def count_vowels(s):
vowels = "aeiouAEIOU"
count = 0
for char in s:
if char in vowels:
count += 1
return count

# Example
text = "DevOps Engineer"
print("Vowel count:", count_vowels(text))


# OR


s = "Interview"
vowels = "aeiouAEIOU"
count = sum(1 for ch in s if ch in vowels)
print(count) # 4

5. Check if a string is a palindrome.

s = "madam"
print(s == s[::-1]) # True


# OR


def is_palindrome(s):
s = s.lower().replace(" ", "") # normalize string
return s == s[::-1]

# Example
print(is_palindrome("madam")) # True
print(is_palindrome("DevOps")) # False

6. Find factorial of a number.

import math
print(math.factorial(5)) # 120



# OR


# Or recursive
def factorial(n):
result = 1
for i in range(2, n + 1):
result *= i
return result

# Example
print(factorial(5)) # 120

7. Find Fibonacci sequence up to n.

def fibonacci(n):
seq = []
a, b = 0, 1
for _ in range(n):
seq.append(a)
a, b = b, a + b
return seq

# Example
print(fibonacci(10)) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

8. Check if a number is prime.

def is_prime(n):
if n <= 1:
return False
for i in range(2, n):
if n % i == 0:
return False
return True

# Example
print(is_prime(7)) # True
print(is_prime(10)) # False

--

--