Day 5: Python Basics for DevOps

Hari Kiran BHari Kiran B
5 min read

Learning points:

πŸ”Ή Python Fundamentals – Variables, data types, operators, and control flow.
πŸ”Ή Functions & Modules – Writing reusable functions and using built-in modules.
πŸ”Ή File Handling – Reading and writing files (
open(), read(), write()).
πŸ”Ή Error Handling – Using
try-except blocks to handle exceptions.
πŸ”Ή Working with Lists, Tuples, and Dictionaries – Data manipulation techniques.
πŸ”Ή Installing Packages with pip – Managing external libraries.
πŸ”Ή Basic Scripting for Automation – Writing and executing Python scripts.

LEARN:

Python tutorial by Sandip Das- Click Here

Initial Tasks:

βœ… Task 1: Install Python (Check with python --version) and set up a virtual environment (venv).
βœ… Task 2: Install VS Code or PyCharm for a better coding experience.
βœ… Task 3: Write a simple Python script that prints "Hello, DevOps!".
βœ… Task 4: Explore built-in data types (int, float, str, list, tuple, dict) and perform basic operations.
βœ… Task 5: Write a Python function that takes two numbers as input and returns their sum.
βœ… Task 6: Use Python’s os and sys modules to interact with the system.

Challenge 1: Create a Python program that accepts a user’s name as input and prints a greeting message.

Goal: Learn basic user input handling in Python.

Answer:

# Accept user input
name = input("Enter your name: ")

# Print a greeting message
print(f"Hello, {name}!")

Explanation of the Script:

  • input("Enter your name: ") β†’ Prompts the user for their name.

  • print(f"Hello, {name}!") β†’ Displays a greeting message.


Challenge 2: Write a script that reads a text file and counts the number of words in it.

Goal: Learn file reading and text processing in Python.

Answer:

# Define the filename
filename = "sample.txt"

# Open the file and count words
with open(filename, "r") as file:
    words = file.read().split()

print(f"Word count: {len(words)}")

Explanation of the Script:

  • open(filename, "r") β†’ Opens the file in read mode.

  • file.read().split() β†’ Reads the content and splits it into words.

  • len(words) β†’ Counts the number of words.


Challenge 3: Create a Python script that generates a random password of 12 characters.

Goal: Learn to generate random passwords.

Answer:

import random
import string

# Generate a random password
password = "".join(random.choices(string.ascii_letters + string.digits, k=12))

print(f"Generated password: {password}")

Explanation of the Script:

  • random.choices() β†’ Picks random characters from letters and digits.

  • "".join(... ) β†’ Joins selected characters into a single string.


Challenge 4: Implement a Python program that checks if a number is prime.

Goal: Learn number theory and efficient prime checking.

Answer:

# Get user input
num = int(input("Enter a number: "))

# Check for prime
if num > 1 and all(num % i != 0 for i in range(2, int(num**0.5) + 1)):
    print(f"{num} is a prime number.")
else:
    print(f"{num} is not a prime number.")

Explanation of the Script:

  • all(num % i != 0 for i in range(2, int(num**0.5) + 1)) β†’ Efficiently checks divisibility up to square root of num.

  • if num > 1 β†’ Ensures numbers below 2 are not prime.


Challenge 5: Write a script that reads a list of server names from a file and pings each one.

Goal: Learn network automation using Python.

Answer:

import os

# Read server names from a file and ping each
with open("servers.txt") as file:
    for server in file:
        os.system(f"ping -c 1 {server.strip()}")

Explanation of the Script:

  • open("servers.txt") β†’ Opens the file containing server names.

  • os.system(f"ping -c 1 {server.strip()}") β†’ Pings each server once.


Challenge 6: Use the requests module to fetch and display data from a public API.

Goal: Learn to make API requests in Python.

Answer:

import requests

# Define the API URL
url = "https://jsonplaceholder.typicode.com/posts/1"

# Fetch data from the API
response = requests.get(url)

# Check if the request was successful
if response.status_code == 200:
    data = response.json()
    print("βœ… Data fetched successfully:")
    print(data)
else:
    print(f"❌ Failed to fetch data. Status code: {response.status_code}")

Explanation of the Script:

  • requests.get(url) β†’ Sends a GET request to the API.

  • response.status_code == 200 β†’ Checks if the request was successful.

  • response.json() β†’ Converts the API response to a Python dictionary.


Challenge 7: Automate a simple task using Python (Rename multiple files in a directory).

Goal: Learn file operations in Python.

Answer:

import os

# Define the target directory
directory = "files"

# Rename files in the directory
for i, filename in enumerate(os.listdir(directory), 1):
    old_path = os.path.join(directory, filename)
    new_path = os.path.join(directory, f"file_{i}.txt")

    os.rename(old_path, new_path)

print("βœ… Files renamed successfully.")

Explanation of the Script:

  • os.listdir(directory) β†’ Lists all files in the specified directory.

  • os.path.join(directory, filename) β†’ Constructs full file paths.

  • os.rename(old_path, new_path) β†’ Renames files sequentially (e.g., file_1.txt, file_2.txt).


Challenge 8: Create a Python script that monitors CPU and memory usage every 5 seconds.

Goal: Learn system monitoring in Python.

Answer:

import psutil
import time

# Monitor system resources
while True:
    cpu_usage = psutil.cpu_percent()
    memory_usage = psutil.virtual_memory().percent

    print(f"CPU Usage: {cpu_usage}% | Memory Usage: {memory_usage}%")

    time.sleep(5)  # Wait for 5 seconds before the next check

Explanation of the Script:

  • psutil.cpu_percent() β†’ Gets the current CPU usage percentage.

  • psutil.virtual_memory().percent β†’ Gets the memory (RAM) usage percentage.

  • time.sleep(5) β†’ Waits for 5 seconds before checking again.


Challenge 9: Write a Python program that creates a user in Linux using subprocess and verifies the creation.

Goal: Learn to manage Linux users using Python.

Answer:

import subprocess

# Define the username
username = "testuser"

# Create a new user
subprocess.run(["sudo", "useradd", username])

# Verify the user creation
result = subprocess.run(["id", username], capture_output=True, text=True)

# Check if user exists
if result.returncode == 0:
    print(f"βœ… User '{username}' created successfully.")
else:
    print(f"❌ Failed to create user '{username}'.")

Explanation of the Script:

  • subprocess.run(["sudo", "useradd", username]) β†’ Creates a new user using useradd (requires sudo).

  • subprocess.run(["id", username], capture_output=True, text=True) β†’ Checks if the user exists.

  • result.returncode == 0 β†’ If the command succeeds, the user was created successfully.

0
Subscribe to my newsletter

Read articles from Hari Kiran B directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Hari Kiran B
Hari Kiran B