Python Basics for DevOps

Table of contents
- Learning points:
- β
Challenge 1: Create a Python program that accepts a userβs name as input and prints a greeting message.
- β Output :
- π Explanation:
- β Challenge 2: Write a script that reads a text file and counts the number of words in it.
- Solution 1: Basic Word Count
- π Explanation:
- Step 2: Create a Sample Text File (Linux/macOS)
- Step 3: Run the Script
- β Output :
- Bonus: Improved Version (Handles Large Files Efficiently) (challenge2_word-count_V.2 .py)
- Why This Version is Better?
- β Challenge 3: Create a Python script that generates a random password of 12 characters.
- Solution: Using random and string Modules
- π Explanation:
- β Output :
- π Explanation:
- β Output :
- β Challenge 4: Implement a Python program that checks if a number is prime.
- Explanation:
- Example Runs:
- β Output :
- Why is This Efficient?
- β 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)
- β Step 2: Python Script to Ping Servers (challenge5_ping-servers.py)
- π Explanation:
- β Step 3: Running the Script
- β Output :
- Bonus: Store Results in a Log File (ping_results.log)
- π Explanation of Log File Enhancement:
- π Why is This Script Useful?
- β 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)
- π Explanation of the Code:
- β Step 3: Run the Script
- π Bonus: Fetch Multiple Posts
- Example Output (Fetching Multiple Posts):
- π Why is This Useful?
- β Challenge 7: Automate a simple task using Python (e.g., renaming multiple files in a directory).
- β Step 1: Create a Directory with Sample Files
- β Step 2: Python Script to Rename Files (challenge7_rename-files.py)
- π Explanation of the Code:
- β Step 3: Run the Script
- β Output :
- π Bonus: Rename Files with a Specific Extension
- π Why is This Useful?
- β Challenge 8: Create a Python script that monitors CPU and memory usage every 5 seconds.
- β Step 1: Install Required Module
- β Step 2: Python Script to Monitor CPU & Memory (monitor_system.py)
- Code:
- π Explanation of the Code:
- β Step 3: Run the Script
- β Output :
- π Bonus: Save Logs to a File
- π Why is This Useful?
- β Challenge 9: Write a Python program that creates a user in Linux using subprocess and verifies the creation.
- π Explanation of the Code:
- β Step 2: Run the Script
- β Input and Output :
- π Bonus: Check If the User Already Exists Before Creation
- β Why is This Useful?
- Thanks for your time. I hope you enjoy my blog, please follow me on LinkedIn for more updates.

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
andb
).
- Defines a function named
Return Statement (
return a + b
)- The function calculates the sum of
a
andb
and returns the result.
- The function calculates the sum of
Function Call (
add_numbers(5, 7)
)- Calls the function with
5
and7
as arguments.
- Calls the function with
Printing the Result (
print("Sum:", result)
)- Displays the returned sum, which is
12
.
- Displays the returned sum, which is
β 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:
input("Enter your name: ")
- This asks the user to enter their name and stores it in the
user_name
variable.
- This asks the user to enter their name and stores it in the
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 withuser_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:
input("Enter the file name: ")
- Takes the file name from the user.
with open(file_name, "r") as file:
- Opens the file in read mode.
content =
file.read
()
- Reads the entire file content into a string.
len(content.split())
Splits the string into words using whitespace as the separator.
Counts the number of words.
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:
Import Modules (
random
,string
)random.choice()
helps select random characters.string
provides predefined sets of characters (letters, digits, punctuation).
Define
generate_password()
FunctionDefault password length is
12
characters.Uses
string.ascii_letters
(A-Z, a-z),string.digits
(0-9), andstring.punctuation
(!@#$%^&*
, etc.).Uses
random.choice()
in a loop to select random characters and joins them into a string.
Function Call and Output
- Calls
generate_password()
and prints the generated password.
- Calls
β 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:
Use
secrets
Module Instead ofrandom
secrets.choice()
provides cryptographically secure random selection.Preferred for generating passwords over
random.choice()
.
Check Minimum Length (8 Characters)
- Ensures security by rejecting passwords shorter than 8 characters.
Character Set (
string
Module)- Uses
string.ascii_letters
(A-Z, a-z),string.digits
(0-9), andstring.punctuation
(!@#$%^&*
, etc.).
- Uses
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:
Function
is_prime(number)
Returns
False
if the number is less than2
(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.
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:
ping_server(server)
functionUses
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
), elseFalse
.
Reads Server Names from
servers.txt
Opens
servers.txt
and reads each line.Strips whitespace (
.strip()
) to remove extra spaces.
Loops Through Each Server and Pings It
Calls
ping_server()
.Prints
β Reachable
if successful, otherwiseβ Unreachable
.
Handles Errors Gracefully
Catches
FileNotFoundError
ifservers.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:
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.
Example Output in Terminal:
google.com: β
Reachable
example.com: β
Reachable
invalid.server: β Unreachable
- 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:
Import
requests
module- This module is used to send HTTP requests.
Define API URL
- We are using
https://jsonplaceholder.typicode.com/posts/1
, a free public API that returns fake JSON data.
- We are using
Send an HTTP GET Request
requests.get(API_URL)
fetches data from the API.
Check Response Status
If the API returns 200 OK, the script proceeds.
Otherwise, it prints an error message with the HTTP status code.
Convert Response to JSON
response.json()
converts the API response into a Python dictionary.
Print API Data
- Extracts and prints the title and body from the JSON response.
Handle Errors Gracefully
- Catches network issues or invalid API responses with
requests.exceptions.RequestException
.
- Catches network issues or invalid API responses with
β 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:
Import
os
module- Used to interact with the file system.
Define the Target Directory
directory = "test_files"
(Modify if needed).
Check If the Directory Exists
- Prevents errors if the directory is missing.
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.
Print Confirmation Messages
- Displays which files were renamed.
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:
Import
psutil
andtime
psutil
is used to get system resource stats.time.sleep(5)
ensures the script runs every 5 seconds.
Define
monitor_system()
FunctionRuns 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.
Handle Keyboard Interrupt (
Ctrl + C
)- Gracefully stops the script when the user presses
Ctrl + C
.
- Gracefully stops the script when the user presses
β 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:
Import
subprocess
- Used to run Linux commands inside Python.
Define
create_user(username)
Uses
subprocess.run(["sudo", "useradd", username], check=True)
to create the user.If the command fails, it raises an error.
Verify User Creation
Runs
id <username>
to check if the user exists.If the command succeeds (
returncode == 0
), it prints user details.
Handle Errors
- If
useradd
fails (e.g., user already exists), it catches the error and prints an appropriate message.
- If
β 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.
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."