Python Basics for DevOps

GOUROB DASGOUROB DAS
18 min read

Table of contents

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.

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!".

pease watch this video for setup python click here

  • βœ… Output :

βœ… Task 4: Explore built-in data types (int, float, str, list, tuple, dict) and perform basic operations.

  • Try the following code in Python:

  •   # Integer (int)
      num1 = 10
      print(type(num1))  # Output: <class 'int'>
    
      # Floating-point number (float)
      num2 = 3.14
      print(type(num2))  # Output: <class 'float'>
    
      # String (str)
      message = "DevOps is great!"
      print(type(message))  # Output: <class 'str'>
    
      # List (Mutable, ordered collection)
      my_list = [1, 2, 3, "DevOps"]
      print(type(my_list))  # Output: <class 'list'>
    
      # Tuple (Immutable, ordered collection)
      my_tuple = (10, 20, 30, "Python")
      print(type(my_tuple))  # Output: <class 'tuple'>
    
      # Dictionary (Key-value pairs)
      my_dict = {"name": "DevOps", "year": 2025}
      print(type(my_dict))  # Output: <class 'dict'>
    
  • Explanation

  • Integer (int): Whole numbers without decimals (e.g., 10).

  • Float (float): Numbers with decimals (e.g., 3.14).

  • String (str): A sequence of characters (e.g., "DevOps is great!").

  • List (list): A mutable (changeable) collection of elements (e.g., [1, 2, 3, "DevOps"]).

  • Tuple (tuple): An immutable (unchangeable) collection of elements (e.g., (10, 20, 30, "Python")).

  • Dictionary (dict): A key-value pair structure (e.g., {"name": "DevOps", "year": 2025}).

Each print(type(variable)) statement outputs the data type of the variable.

  • βœ… Output :

βœ… Task 5: Write a Python function that takes two numbers as input and returns their sum.

  • Try the following code in Python:

  •   def add_numbers(a, b):
          """
          This function takes two numbers as input and returns their sum.
          """
          return a + b
    
      # Example usage
      result = add_numbers(5, 7)
      print("Sum:", result)  # Output: Sum: 12
    
  • Explanation

  • Function Definition (def add_numbers(a, b):)

    • Defines a function named add_numbers that accepts two parameters (a and b).
  • Return Statement (return a + b)

    • The function calculates the sum of a and b and returns the result.
  • Function Call (add_numbers(5, 7))

    • Calls the function with 5 and 7 as arguments.
  • Printing the Result (print("Sum:", result))

    • Displays the returned sum, which is 12.
  • βœ… Output :

βœ… Task 6: Use Python’s os and sys modules to interact with the system.

  • Try the following code in Python:

  •   import os
      import sys
    
      # Get the current working directory
      cwd = os.getcwd()
      print("Current Working Directory:", cwd)
    
      # List files in the current directory
      files = os.listdir()
      print("Files in Directory:", files)
    
      # Get the Python version
      print("Python Version:", sys.version)
    
      # Get the script name
      print("Script Name:", sys.argv[0])
    
  • Explanation

  • Importing Modules (import os, sys)

    • The os module provides functions for interacting with the operating system.

    • The sys module provides functions and variables related to the Python runtime.

  • Get Current Working Directory (os.getcwd())

    • Retrieves and prints the directory where the script is being executed.
  • List Files in the Directory (os.listdir())

    • Returns and prints a list of files and folders in the current directory.
  • Get Python Version (sys.version)

    • Displays the Python version currently in use.
  • Get Script Name (sys.argv[0])

    • Prints the name of the script being executed.
  • βœ… Output :


πŸ”₯ Challenges

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

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

πŸ”Ή Challenge 3: Create a Python script that generates a random password of 12 characters.

πŸ”Ή Challenge 4: Implement a Python program that checks if a number is prime.

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

πŸ”Ή Challenge 6: Use the requests module to fetch and display data from a public API (e.g., JSONPlaceholder).

πŸ”Ή Challenge 7: Automate a simple task using Python (e.g., renaming multiple files in a directory).

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

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


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

Try the following code in Python:

# Prompt the user to enter their name
user_name = input("Enter your name: ")

# Print a greeting message
print("Hello, " + user_name + "! Welcome to DevOps learning.")

Run this file:

Challenge1_greeting-to-user.py

βœ… Output :

πŸ›  Explanation:

  1. input("Enter your name: ")

    • This asks the user to enter their name and stores it in the user_name variable.
  2. print("Hello, " + user_name + "! Welcome to DevOps learning.")

    • This prints a personalized greeting using the entered name.

    • The + operator is used to concatenate the string with user_name.


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

Solution 1: Basic Word Count

Code:

# 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}")

πŸ›  Explanation:

  1. input("Enter the file name: ")

    • Takes the file name from the user.
  2. with open(file_name, "r") as file:

    • Opens the file in read mode.
  3. content = file.read()

    • Reads the entire file content into a string.
  4. len(content.split())

    • Splits the string into words using whitespace as the separator.

    • Counts the number of words.

  5. Exception Handling:

    • FileNotFoundError: Catches cases where the file doesn't exist.

    • Exception as e: Catches other unexpected errors.

Step 2: Create a Sample Text File (Linux/macOS)

Run this command to create a text file:

echo "DevOps is about automation, collaboration, and efficiency." > sample.txt

Step 3: Run the Script

Execute the script and provide the filename:

challenge2_word-count.py

Example Input:

Enter the file name: sample.txt

βœ… Output :

Bonus: Improved Version (Handles Large Files Efficiently) (challenge2_word-count_V.2 .py)

Code:

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}")

Why This Version is Better?

βœ… Reads Line by Line:

  • Avoids loading the entire file into memory (better for large files).
    βœ… Counts Words More Efficiently:

  • Reads each line separately and updates the word count dynamically.


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

Solution: Using random and string Modules

Code:

import random
import string

def generate_password(length=12):
    """
    Generates a random password with uppercase, lowercase, digits, and special characters.
    """
    # Define the character set
    characters = string.ascii_letters + string.digits + string.punctuation

    # Generate a random password of the specified length
    password = ''.join(random.choice(characters) for _ in range(length))

    return password

# Generate and print the password
random_password = generate_password()
print("πŸ”‘ Generated Password:", random_password)

Example Input:

python challenge3_Random-12-Character-generator.py

πŸ›  Explanation:

  1. Import Modules (random, string)

    • random.choice() helps select random characters.

    • string provides predefined sets of characters (letters, digits, punctuation).

  2. Define generate_password() Function

    • Default password length is 12 characters.

    • Uses string.ascii_letters (A-Z, a-z), string.digits (0-9), and string.punctuation (!@#$%^&*, etc.).

    • Uses random.choice() in a loop to select random characters and joins them into a string.

  3. Function Call and Output

    • Calls generate_password() and prints the generated password.

βœ… Output :

Each run generates a unique password! πŸš€

Bonus: Modify the script to allow user-defined password length: (file name - β€œ v.2-challenge3_Random-12-Character-generator.pyβ€œ

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}")

πŸ›  Explanation:

  1. Use secrets Module Instead of random

    • secrets.choice() provides cryptographically secure random selection.

    • Preferred for generating passwords over random.choice().

  2. Check Minimum Length (8 Characters)

    • Ensures security by rejecting passwords shorter than 8 characters.
  3. Character Set (string Module)

    • Uses string.ascii_letters (A-Z, a-z), string.digits (0-9), and string.punctuation (!@#$%^&*, etc.).
  4. Handle User Input (try-except)

    • Converts input to an integer.

    • Catches ValueError if the user enters non-numeric input.

βœ… Output :

βœ… Valid Input:

bashCopyEditEnter password length (min 8): 12
πŸ” Your secure password: G@9z!Kb$P4d%

❌ Invalid Input (Too Short):

bashCopyEditEnter password length (min 8): 5
❌ Password length should be at least 8 characters for security.

❌ Invalid Input (Non-Numeric):

bashCopyEditEnter password length (min 8): abc
❌ Invalid input! Please enter a valid number.

πŸš€ This version ensures security, flexibility, and robustness!


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

Code:

def is_prime(number):
    """
    Checks if a given number is a prime number.
    """
    if number < 2:
        return False  # Numbers less than 2 are not prime

    for i in range(2, int(number ** 0.5) + 1):  # Check divisibility up to √number
        if number % i == 0:
            return False  # If divisible, it's not prime

    return True  # If no divisors found, it's prime

# Ask the user for input
try:
    num = int(input("Enter a number: "))

    # Check and print result
    if is_prime(num):
        print(f"βœ… {num} is a prime number.")
    else:
        print(f"❌ {num} is not a prime number.")

except ValueError:
    print("❌ Invalid input! Please enter a valid integer.")

Explanation:

  1. Function is_prime(number)

    • Returns False if the number is less than 2 (since 0 and 1 are not prime).

    • Loops from 2 to √number to check divisibility.

    • If the number is divisible by any number in this range, it's not prime.

    • Otherwise, it's a prime number.

  2. User Input Handling (try-except)

    • Converts user input to an integer.

    • Catches ValueError if the input is not a valid number.

Example Input:

python challenge4_check_prime-number.py

Example Runs:

βœ… Prime Number Input:

Enter a number: 17
βœ… 17 is a prime number.

❌ Non-Prime Number Input:

Enter a number: 20
❌ 20 is not a prime number.

❌ Invalid Input:

Enter a number: abc
❌ Invalid input! Please enter a valid integer.

βœ… Output :

Why is This Efficient?

πŸ”Ή Iterates Only Up to √n instead of checking all numbers up to n.
πŸ”Ή Handles Edge Cases like negative numbers, 0, and 1.


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

βœ… Step 1: Creating the Server List File (servers.txt)

echo -e "google.com\nexample.com\ninvalid.server" > servers.txt
  • This creates a file named servers.txt that contains:

      google.com
      example.com
      invalid.server
    
  • The script will read this file to get the list of servers to ping.


βœ… Step 2: Python Script to Ping Servers (challenge5_ping-servers.py)

Code:

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}")

πŸ” Explanation:

  1. ping_server(server) function

    • Uses os.system() to send a ping request to the server.

    • Checks the operating system:

      • -n 1 for Windows

      • -c 1 for Linux/macOS

    • Suppresses output (> /dev/null 2>&1 for Unix, > nul for Windows).

    • Returns True if the server responds (ping successful), else False.

  2. Reads Server Names from servers.txt

    • Opens servers.txt and reads each line.

    • Strips whitespace (.strip()) to remove extra spaces.

  3. Loops Through Each Server and Pings It

    • Calls ping_server().

    • Prints βœ… Reachable if successful, otherwise ❌ Unreachable.

  4. Handles Errors Gracefully

    • Catches FileNotFoundError if servers.txt is missing.

    • Catches any other unexpected errors and prints them.


βœ… Step 3: Running the Script

python challenge5_ping-servers.py

Example Output:

google.com: βœ… Reachable
example.com: βœ… Reachable
invalid.server: ❌ Unreachable

βœ… Output :


Bonus: Store Results in a Log File (ping_results.log)

Code:

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}")

πŸ” Explanation of Log File Enhancement:

  1. Stores Results in ping_results.log

    • Opens ping_results.log in write mode ("w").

    • Logs each server's status into the file.

    • Keeps printing the results in the terminal as well.

  2. Example Output in Terminal:

google.com: βœ… Reachable
example.com: βœ… Reachable
invalid.server: ❌ Unreachable
  1. Example ping_results.log File Contents:
google.com: βœ… Reachable
example.com: βœ… Reachable
invalid.server: ❌ Unreachable

πŸš€ Why is This Script Useful?

βœ… Automates server health checks
βœ… Works on Linux, Mac, and Windows
βœ… Stores logs for future reference


βœ… Challenge 6: Use the requests module to fetch and display data from a public API (e.g., JSONPlaceholder).

βœ… Step 1: Install Requests Module (if not installed)

Run this in your terminal if requests is not installed:

pip install requests

βœ… Step 2: Python Script to Fetch API Data (challenge6_fetch_api_data.py)

Code:

import requests

# Define the API URL (Using JSONPlaceholder for fake data)
API_URL = "https://jsonplaceholder.typicode.com/posts/1"

try:
    # Send GET request to fetch data from API
    response = requests.get(API_URL)

    # Check if the request was successful (HTTP status code 200)
    if response.status_code == 200:
        data = response.json()  # Convert response to JSON format

        # Print the fetched data
        print("βœ… API Response:")
        print(f"Title: {data['title']}")
        print(f"Body: {data['body']}")
    else:
        print(f"❌ Error: API returned status code {response.status_code}")

except requests.exceptions.RequestException as e:
    print(f"❌ An error occurred: {e}")

πŸ” Explanation of the Code:

  1. Import requests module

    • This module is used to send HTTP requests.
  2. Define API URL

  3. Send an HTTP GET Request

    • requests.get(API_URL) fetches data from the API.
  4. Check Response Status

    • If the API returns 200 OK, the script proceeds.

    • Otherwise, it prints an error message with the HTTP status code.

  5. Convert Response to JSON

    • response.json() converts the API response into a Python dictionary.
  6. Print API Data

    • Extracts and prints the title and body from the JSON response.
  7. Handle Errors Gracefully

    • Catches network issues or invalid API responses with requests.exceptions.RequestException.

βœ… Step 3: Run the Script

python challenge6_fetch_api_data.py

βœ… Output :

πŸš€ Bonus: Fetch Multiple Posts

To get multiple posts, modify the script like this:

API_URL = "https://jsonplaceholder.typicode.com/posts"

try:
    response = requests.get(API_URL)

    if response.status_code == 200:
        posts = response.json()

        print("βœ… API Response:")
        for post in posts[:5]:  # Print only first 5 posts
            print(f"\nπŸ”Ή Title: {post['title']}")
            print(f"   Body: {post['body']}")
    else:
        print(f"❌ Error: API returned status code {response.status_code}")

except requests.exceptions.RequestException as e:
    print(f"❌ An error occurred: {e}")

Example Output (Fetching Multiple Posts):

βœ… API Response:

πŸ”Ή Title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit
   Body: quia et suscipit suscipit recusandae consequuntur...

πŸ”Ή Title: qui est esse
   Body: est rerum tempore vitae...

πŸ”Ή Title: ea molestias quasi exercitationem repellat qui ipsa sit aut
   Body: et iusto sed quo iure...

πŸš€ Why is This Useful?

βœ… Automates API testing & data fetching
βœ… Can be extended for real-world APIs (e.g., GitHub, Weather, Finance)
βœ… Demonstrates error handling for reliable scripts


βœ… Challenge 7: Automate a simple task using Python (e.g., renaming multiple files in a directory).

βœ… Step 1: Create a Directory with Sample Files

Before running the script, create a test directory with some sample files:

mkdir test_files
cd test_files
touch file1.txt file2.txt file3.txt
cd ..

βœ… Step 2: Python Script to Rename Files (challenge7_rename-files.py)

Code:

import os

# Define the directory containing files
directory = "test_files"

try:
    # Check if the directory exists
    if not os.path.exists(directory):
        print(f"❌ Error: The directory '{directory}' does not exist.")
        exit()

    # Loop through files in the directory
    for count, filename in enumerate(os.listdir(directory), start=1):
        old_path = os.path.join(directory, filename)  # Get full file path

        # Define the new file name format
        new_filename = f"renamed_file_{count}.txt"
        new_path = os.path.join(directory, new_filename)

        # Rename the file
        os.rename(old_path, new_path)

        print(f"βœ… Renamed '{filename}' β†’ '{new_filename}'")

except Exception as e:
    print(f"❌ An error occurred: {e}")

πŸ” Explanation of the Code:

  1. Import os module

    • Used to interact with the file system.
  2. Define the Target Directory

    • directory = "test_files" (Modify if needed).
  3. Check If the Directory Exists

    • Prevents errors if the directory is missing.
  4. Loop Through Files and Rename Them

    • enumerate(os.listdir(directory), start=1) gets all files and numbers them.

    • Creates a new filename format: "renamed_file_1.txt", "renamed_file_2.txt", ...

    • Uses os.rename(old_path, new_path) to rename files.

  5. Print Confirmation Messages

    • Displays which files were renamed.
  6. Handle Errors

    • Catches and reports any exceptions.

βœ… Step 3: Run the Script

python challenge7_rename-files.py

βœ… Output :


πŸš€ Bonus: Rename Files with a Specific Extension

Modify the script to rename only .txt files:

for count, filename in enumerate(os.listdir(directory), start=1):
    if filename.endswith(".txt"):  # Only rename .txt files
        old_path = os.path.join(directory, filename)
        new_filename = f"document_{count}.txt"
        new_path = os.path.join(directory, new_filename)
        os.rename(old_path, new_path)
        print(f"βœ… Renamed '{filename}' β†’ '{new_filename}'")

πŸš€ Why is This Useful?

βœ… Automates tedious file renaming tasks
βœ… Can be modified to organize images, logs, reports, etc.
βœ… Saves time when managing large datasets


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

βœ… Step 1: Install Required Module

The psutil module is used to get system resource usage. Install it using:

pip install psutil

βœ… Step 2: Python Script to Monitor CPU & Memory (monitor_system.py)

Code:

import psutil
import time

def monitor_system():
    """Continuously monitor CPU and memory usage every 5 seconds."""
    try:
        while True:
            # Get CPU and memory usage
            cpu_usage = psutil.cpu_percent(interval=1)  # CPU usage in percentage
            memory_info = psutil.virtual_memory()  # Memory usage details

            # Print system usage statistics
            print(f"πŸ”² CPU Usage: {cpu_usage}% | ⛁ Memory Usage: {memory_info.percent}%")

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

    except KeyboardInterrupt:
        print("\nπŸ›‘ Monitoring stopped by user.")

# Run the monitoring function
monitor_system()

πŸ” Explanation of the Code:

  1. Import psutil and time

    • psutil is used to get system resource stats.

    • time.sleep(5) ensures the script runs every 5 seconds.

  2. Define monitor_system() Function

    • Runs an infinite loop to check CPU and memory usage.

    • Uses psutil.cpu_percent(interval=1) to get CPU usage.

    • Uses psutil.virtual_memory().percent to get memory usage.

  3. Handle Keyboard Interrupt (Ctrl + C)

    • Gracefully stops the script when the user presses Ctrl + C.

βœ… Step 3: Run the Script

python monitor_system.py

βœ… Output :


πŸš€ Bonus: Save Logs to a File

Modify the script to store logs in system_usage.log:

pythonCopyEditwith open("system_usage.log", "a") as log_file:
    while True:
        cpu_usage = psutil.cpu_percent(interval=1)
        memory_info = psutil.virtual_memory().percent
        log_entry = f"CPU: {cpu_usage}% | Memory: {memory_info}%\n"

        print(log_entry.strip())  # Print to console
        log_file.write(log_entry)  # Write to log file

        time.sleep(5)

πŸš€ Why is This Useful?

βœ… Helps track system performance over time
βœ… Can detect high CPU/memory usage issues
βœ… Useful for DevOps, server monitoring, and performance debugging


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

βœ… Step 1: Python Script to Create and Verify a User (challenge9_create-user.py)

Code:

import subprocess

def create_user(username):
    """Creates a Linux user and verifies the creation."""
    try:
        # Create the user (Runs `sudo useradd <username>`)
        subprocess.run(["sudo", "useradd", username], check=True)
        print(f"βœ… User '{username}' created successfully.")

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

        if result.returncode == 0:
            print(f"πŸ” User verification successful:\n{result.stdout}")
        else:
            print(f"❌ User verification failed: {result.stderr}")

    except subprocess.CalledProcessError as e:
        print(f"❌ Error: Failed to create user '{username}'. {e}")

# Ask for username input
username = input("Enter the new username: ")
create_user(username)

πŸ” Explanation of the Code:

  1. Import subprocess

    • Used to run Linux commands inside Python.
  2. Define create_user(username)

    • Uses subprocess.run(["sudo", "useradd", username], check=True) to create the user.

    • If the command fails, it raises an error.

  3. Verify User Creation

    • Runs id <username> to check if the user exists.

    • If the command succeeds (returncode == 0), it prints user details.

  4. Handle Errors

    • If useradd fails (e.g., user already exists), it catches the error and prints an appropriate message.

βœ… Step 2: Run the Script

python challenge9_create-user.py

βœ… Input and Output :


πŸš€ Bonus: Check If the User Already Exists Before Creation

Modify the script to check if the user exists before running useradd:

def user_exists(username):
    """Checks if a user already exists in the system."""
    result = subprocess.run(["id", username], capture_output=True, text=True)
    return result.returncode == 0

username = input("Enter the new username: ")

if user_exists(username):
    print(f"⚠️ User '{username}' already exists!")
else:
    create_user(username)

βœ… Why is This Useful?

βœ”οΈ Automates Linux user creation
βœ”οΈ Ensures user is successfully created
βœ”οΈ Prevents duplicate user creation


Thanks for your time. I hope you enjoy my blog, please follow me on LinkedIn for more updates.

0
Subscribe to my newsletter

Read articles from GOUROB DAS directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

GOUROB DAS
GOUROB DAS

About "Hello! My name is Gourob Das, I completed my GSSOC as an open source Contributor, I completed a 4-month internship at Dpay Consultancy Services as an application developer, and completed my MCA Degree at Pondicherry University. I am highly passionate about DevOps dedicated to enhancing experiences through the power of artificial intelligence. Let's connect and collaborate on DevOps, cloud Computing development projects."Enjoy exploring the fascinating world of DevOps, constantly seeking to apply cutting-edge technology to solve real-world problems."