60 Days DevOps Challenge: Day 5


Challenge 1: Create a Python program that accepts a userβs name as input and prints a greeting message
Step 1: Create the Python Script (greet.py
)
# Ask for user input
name = input("Enter your name: ")
# Print a greeting message
print(f"Hello, {name}! Welcome to the DevOps world! π")
Step 2: Run the Script
Save the file as greet.py
, then execute it in a terminal:
python greet.py
Output:
Enter your name: Musaveer
Hello, Musaveer! Welcome to the DevOps world! π
Challenge 2: Write a script that reads a text file and counts the number of words in it.
Step 1: Create the Python Script (word_count.py)
# Ask for the file name
file_name = input("Enter the file name: ")
try:
# Open and read the file
with open(file_name, "r") as file:
content = file.read()
# Count words
word_count = len(content.split())
# Print the word count
print(f"β
The file '{file_name}' contains {word_count} words.")
except FileNotFoundError:
print(f"β Error: The file '{file_name}' was not found.")
except Exception as e:
print(f"β An error occurred: {e}")
Step 2: Create a Sample Text File (sample.txt)
echo "DevOps is about automation, collaboration, and efficiency." > sample.txt
Step 3: Run the Script
Execute the script and provide the filename:
python word_count.py
Example Input:
Enter the file name: sample.txt
Example Output:
Enter the file name: sample.txt
β
The file 'sample.txt' contains 7 words.
Bonus: Improve the Script
To handle large files efficiently, modify it to read line by line:
file_name = input("Enter the file name: ")
try:
word_count = 0
with open(file_name, "r") as file:
for line in file:
word_count += len(line.split())
print(f"β
The file '{file_name}' contains {word_count} words.")
except FileNotFoundError:
print(f"β Error: The file '{file_name}' was not found.")
except Exception as e:
print(f"β An error occurred: {e}")
Challenge 3: Create a Python script that generates a random password of 12 characters.
Step 1: Create the Python Script (generate_password.py)
import secrets
import string
def generate_password(length=12):
# Define the character set: letters, digits, and special characters
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(secrets.choice(characters) for _ in range(length))
return password
# Generate and print a random password
print(f"π Your secure password: {generate_password()}")
Step 2: Run the Script
python generate_
password.py
Example Output
π Your secure password: lGd;@_;n#zXC
Bonus: Modify the script to allow user-defined password length:
def generate_password(length):
if length < 8:
print("β Password length should be at least 8 characters for security.")
return None
characters = string.ascii_letters + string.digits + string.punctuation
return ''.join(secrets.choice(characters) for _ in range(length))
# Ask user for password length
length = int(input("Enter password length (min 8): "))
password = generate_password(length)
if password:
print(f"π Your secure password: {password}")
Challenge 4: Implement a Python program that checks if a number is prime.
Step 1: Create the Python Script (check_prime.py)
def is_prime(n):
"""Check if a number is prime."""
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
# Get user input
try:
num = int(input("Enter a number: "))
# Check if it's prime and print the result
if is_prime(num):
print(f"β
{num} is a prime number.")
else:
print(f"β {num} is not a prime number.")
except ValueError:
print("β Please enter a valid integer.")
Step 2: Run the Script
python check_prime.py
Example Outputs
For a prime number (e.g., 13)
Enter a number: 13
13 is a prime number.
For a non-prime number (e.g., 15)
Enter a number: 15
15 is not a prime number.
For invalid input (e.g., abc)
Please enter a valid integer.
Challenge 5: Write a script that reads a list of server names from a file and pings each one.
Step 1: Create the Server List File (servers.txt)
echo -e "google.com\nexample.com\ninvalid.server" > servers.txt
This file contains:
google.com
example.com
invalid.server
Step 2: Create the Python Script (ping_servers.py)
import os
import platform
def ping_server(server):
"""Ping a server and return True if reachable, False otherwise."""
param = "-n 1" if platform.system().lower() == "windows" else "-c 1"
response = os.system(f"ping {param} {server} > /dev/null 2>&1")
return response == 0
# Read server names from file
try:
with open("servers.txt", "r") as file:
servers = [line.strip() for line in file.readlines()]
# Ping each server
for server in servers:
if server:
status = "β
Reachable" if ping_server(server) else "β Unreachable"
print(f"{server}: {status}")
except FileNotFoundError:
print("β Error: servers.txt not found!")
except Exception as e:
print(f"β An error occurred: {e}")
Example Output:
google.com: β
Reachable
example.com: β
Reachable
invalid.server: β Unreachable
Bonus π‘ : Store Results in a Log File
import os
import platform
def ping_server(server):
"""Ping a server and return True if reachable, False otherwise."""
param = "-n 1" if platform.system().lower() == "windows" else "-c 1"
response = os.system(f"ping {param} {server} > /dev/null 2>&1")
return response == 0
# Read server names from file
try:
with open("servers.txt", "r") as file:
servers = [line.strip() for line in file.readlines()]
with open("ping_results.log", "w") as log_file:
for server in servers:
if server:
status = "β
Reachable" if ping_server(server) else "β Unreachable"
log_file.write(f"{server}: {status}\n")
print(f"{server}: {status}")
except FileNotFoundError:
print("β Error: servers.txt not found!")
except Exception as e:
print(f"β An error occurred: {e}")
Challenge 6: Use the requests
module to fetch and display data from a public API (e.g., JSONPlaceholder).
Step 1: Install the Requests Module (If Not Installed)
pip install requests
Step 2: Create the Python Script (crud_
call.py
)
import requests
# Define the base API URL
API_URL = "https://jsonplaceholder.typicode.com/posts"
# Function to perform a GET request
def get_post(post_id):
try:
response = requests.get(f"{API_URL}/{post_id}")
if response.status_code == 200:
data = response.json()
print(f"β
GET Request Successful: Fetched Post {post_id}\n")
print(f"Title: {data['title']}\nBody:\n{data['body']}\n")
else:
print(f"β GET Error: Status Code {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"β GET Request Failed: {e}")
# Function to perform a POST request (Create new post)
def create_post():
new_post = {
"title": "New Post",
"body": "This is a new post created via API.",
"userId": 1
}
try:
response = requests.post(API_URL, json=new_post)
if response.status_code == 201:
data = response.json()
print(f"β
POST Request Successful: Created New Post\n")
print(f"Post ID: {data['id']}\nTitle: {data['title']}\nBody:\n{data['body']}\n")
return data['id'] # Return the new post ID for further operations
else:
print(f"β POST Error: Status Code {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"β POST Request Failed: {e}")
# Function to perform a PUT request (Update existing post)
def update_post(post_id):
updated_post = {
"id": post_id,
"title": "Updated Post",
"body": "This post has been updated via API.",
"userId": 1
}
try:
response = requests.put(f"{API_URL}/{post_id}", json=updated_post)
if response.status_code == 200:
data = response.json()
print(f"β
PUT Request Successful: Updated Post {post_id}\n")
print(f"Title: {data['title']}\nBody:\n{data['body']}\n")
else:
print(f"β PUT Error: Status Code {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"β PUT Request Failed: {e}")
# Function to perform a DELETE request
def delete_post(post_id):
try:
response = requests.delete(f"{API_URL}/{post_id}")
if response.status_code == 200 or response.status_code == 204:
print(f"β
DELETE Request Successful: Post {post_id} Deleted\n")
else:
print(f"β DELETE Error: Status Code {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"β DELETE Request Failed: {e}")
# Main execution
if __name__ == "__main__":
# Step 1: Fetch a post
get_post(1)
# Step 2: Create a new post
new_post_id = create_post()
if new_post_id:
# Step 3: Update the created post
update_post(new_post_id)
# Step 4: Delete the created post
delete_post(new_post_id)
Step 3: Run the Script
python crud_call.py
Example Output
β
GET Request Successful: Fetched Post 1
Title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit
Body:
quia et suscipit
suscipit repellat nisi
temporibus atque autem
quasi corporis dolores aperiam
...
(Truncated for readability)
β
POST Request Successful: Created New Post
Post ID: 101
Title: New Post
Body:
This is a new post created via API.
β
PUT Request Successful: Updated Post 101
Title: Updated Post
Body:
This post has been updated via API.
β
DELETE Request Successful: Post 101 Deleted
Challenge 7: Automate a simple task using Python (e.g., renaming multiple files in a directory).
Step 1: First, create some sample files for testing:
mkdir test_files
cd test_files
touch file1.txt file2.txt file3.txt
cd ..
Step 2: Create the Python Script (rename_
files.py
)
import os
# Define the directory containing files
directory = "test_files"
# Define the renaming pattern
prefix = "renamed_"
# Ensure the directory exists
if not os.path.exists(directory):
print(f"β Error: Directory '{directory}' not found!")
exit(1)
# Rename each file in the directory
for count, filename in enumerate(os.listdir(directory), start=1):
old_path = os.path.join(directory, filename)
# Skip directories, rename only files
if os.path.isfile(old_path):
new_name = f"{prefix}{count}.txt"
new_path = os.path.join(directory, new_name)
os.rename(old_path, new_path)
print(f"β
Renamed: {filename} β {new_name}")
print("π Renaming completed!")
Step 3: Run the Script
python rename_files.py
Example Output
β
Renamed: file1.txt β renamed_1.txt
β
Renamed: file2.txt β renamed_2.txt
β
Renamed: file3.txt β renamed_3.txt
π Renaming completed!
Challenge 8: Create a Python script that monitors CPU and memory usage every 5 seconds.
Step 1: Install psutil (If Not Installed)
pip install psutil
Step 2: Create the Python Script (monitor_
resources.py
)
import psutil
import time
def monitor_resources(interval=5):
"""Monitors CPU and memory usage every `interval` seconds."""
print("π Monitoring CPU and Memory usage... (Press Ctrl+C to stop)\n")
try:
while True:
cpu_usage = psutil.cpu_percent(interval=1)
memory_info = psutil.virtual_memory()
memory_usage = memory_info.percent
print(f"π₯οΈ CPU Usage: {cpu_usage}% | π§ Memory Usage: {memory_usage}%")
time.sleep(interval - 1) # Adjust for the CPU check time
except KeyboardInterrupt:
print("\nβ Monitoring stopped.")
# Run the monitoring function
monitor_resources()
Step 3: Run the Script
python monitor_resources.py
Example Output
π Monitoring CPU and Memory usage... (Press Ctrl+C to stop)
π₯οΈ CPU Usage: 12% | π§ Memory Usage: 45%
π₯οΈ CPU Usage: 9% | π§ Memory Usage: 43%
π₯οΈ CPU Usage: 15% | π§ Memory Usage: 47%
β Monitoring stopped.
Bonus π‘ : save the CPU and memory usage data in a log file:
import psutil
import time
def monitor_resources(interval=5, log_file_path="resource_usage.log"):
"""Monitors CPU and memory usage every `interval` seconds and logs it to a file."""
print("π Monitoring CPU and Memory usage... (Press Ctrl+C to stop)\n")
try:
with open(log_file_path, "a") as log_file:
while True:
cpu_usage = psutil.cpu_percent(interval=1)
memory_info = psutil.virtual_memory()
memory_usage = memory_info.percent
log_entry = f"{time.strftime('%Y-%m-%d %H:%M:%S')} | CPU: {cpu_usage}% | Memory: {memory_usage}%\n"
log_file.write(log_entry)
log_file.flush() # Ensure data is written immediately
print(f"π₯οΈ CPU Usage: {cpu_usage}% | π§ Memory Usage: {memory_usage}%")
time.sleep(interval - 1) # Adjust for the CPU check time
except KeyboardInterrupt:
print("\nβ Monitoring stopped.")
# Run the monitoring function
monitor_resources()
Challenge 9: Write a Python program that creates a user in Linux using subprocess
and verifies the creation.
Step 1: Create the Python Script (create_user.py)
import subprocess
def create_user(username):
"""Creates a Linux user and verifies the creation."""
# Check if the user already exists
try:
subprocess.run(["id", username], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
print(f"β
User '{username}' already exists.")
return
except subprocess.CalledProcessError:
pass # User does not exist, continue to create
# Create the user
try:
subprocess.run(["sudo", "useradd", "-m", "-s", "/bin/bash", username], check=True)
print(f"β
User '{username}' created successfully.")
except subprocess.CalledProcessError:
print(f"β Failed to create user '{username}'. Ensure you have sudo privileges.")
return
# Verify user creation
try:
subprocess.run(["id", username], check=True)
print(f"β
Verification successful: '{username}' exists in the system.")
except subprocess.CalledProcessError:
print(f"β Verification failed: '{username}' does not exist.")
# Get username input from the user
username = input("Enter the username to create: ")
create_user(username)
Step 2: Run the Script
Since creating a user requires root privileges, run the script with sudo:
sudo python create_user.py
Example Output
If the user already exists:
Enter the username to create: devops_user
User 'devops_user' already exists.
If the user is created successfully:
Enter the username to create: devops_user
β
User 'devops_user' created successfully.
β
Verification successful: 'devops_user' exists in the system.
If creation fails due to insufficient privileges:
Enter the username to create: devops_user
β Failed to create user 'devops_user'. Ensure you have sudo privileges.
In conclusion, the 60 Days DevOps Challenge: Day 5 offers a diverse set of Python programming tasks that enhance both fundamental and advanced skills. From creating simple scripts for user interaction and file manipulation to more complex tasks like API integration and system monitoring, these challenges provide a comprehensive learning experience. By tackling these exercises, participants can strengthen their problem-solving abilities, improve their coding proficiency, and gain practical insights into DevOps practices. This structured approach not only builds technical expertise but also fosters a deeper understanding of automation and efficiency in software development and operations.
Subscribe to my newsletter
Read articles from Musaveer Holalkere directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
