cancel
Showing results for 
Search instead for 
Did you mean: 
Chetan_Tiwary_
Community Manager
Community Manager
  • 1,316 Views

Solve this Shell Scripting Challenge.

Write a Bash shell script that checks if a user exists in your system. If the user doesn't exist, the script should prompt the user to create the user with a strong password. The script should also ensure that the user's home directory is created.

More marks for clarity, reusability and readability!

Labels (2)
21 Replies
burning_red
Mission Specialist
Mission Specialist
  • 41 Views

#!/bin/bash

# Check if run as root
if [ "$EUID" -ne 0 ]; then
echo "Please run this script as root."
exit 1
fi

# Function to log messages
log_message() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a /var/log/user_creation.log
}

# Prompt for username
read -p "Enter the username you want to check: " username

# Check if user exists
if getent passwd "$username" >/dev/null 2>&1; then
log_message "User $username already exists."
else
# User doesn't exist, prompt for password
read -s -p "Enter a strong password for $username: " password
echo # Newline for better readability

# Hash the password securely
hashed_password=$(echo -n "$password" | openssl passwd -6 -stdin)

# Create the user
useradd -m -G users,wheel "$username"

# Set the password
echo "$username:$hashed_password" | chpasswd

log_message "Created new user $username with home directory and set password."
fi

exit 0

0 Kudos
Rahulkrishnan
Mission Specialist
Mission Specialist
  • 23 Views

#!/bin/bash

# Function to check if a user exists
check_user() {
local username="$1"
if id "$username" &>/dev/null; then
echo "User '$username' already exists."
else
echo "User '$username' does not exist."
create_user "$username"
fi
}

# Function to create a new user with a strong password
create_user() {
local username="$1"
local password=""
local password_length=16
local allowed_chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+|~-=\`{}[]:;'<>?,./'"

# Generate a random strong password
while [ "${#password}" -lt "$password_length" ]; do
password+="${allowed_chars:$((RANDOM%${#allowed_chars})):1}"
done

# Create the user with the generated password
sudo useradd -m "$username"
echo "$username:$password" | sudo chpasswd
echo "User '$username' has been created with a strong password."
}

# Main script execution
echo "Enter the username to check:"
read -r username
check_user "$username"

0 Kudos
Join the discussion
You must log in to join this conversation.