DEV Community

Iyewumi Adesupo
Iyewumi Adesupo

Posted on

Linux User Creation Bash Script

As your company scales and brings in new developers, managing user accounts manually can become cumbersome and error-prone. Automating this process with a Bash script can save time and ensure consistency across the board. In this article, I'll walk you through creating a Bash script called create_users.sh that reads a text file containing usernames and group names, creates the necessary users and groups, sets up home directories, generates random passwords, and logs all actions. Let's dive in!

Requirements
Input File: A text file where each line is formatted as user;groups. Usernames and groups are separated by a semicolon ;, and multiple groups are delimited by a comma ,.
User Creation: Each user must have a personal group with the same name as the username, though this group name will not be written in the text file.
Logging: Log all actions to /var/log/user_management.log.
Password Storage: Store generated passwords securely in /var/secure/user_passwords.csv.
Error Handling: Handle scenarios like existing users gracefully.
Example Input File

light; sudo,dev,www-data
idimma; sudo
mayowa; dev,www-data
Enter fullscreen mode Exit fullscreen mode

The Script
Here is the complete create_users.sh script:


# Log file location
LOGFILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.csv"

# Check if the input file is provided
if [ -z "$1" ]; then
  echo "Error: No file was provided"
  echo "Usage: $0 <name-of-text-file>"
  exit 1
fi

# Create log and password files
mkdir -p /var/secure
touch $LOGFILE $PASSWORD_FILE
chmod 600 $PASSWORD_FILE

generate_random_password() {
    local length=${1:-12} # Default length is 12 if no argument is provided
    LC_ALL=C tr -dc 'A-Za-z0-9!?%+=' < /dev/urandom | head -c $length
}

# Function to create a user
create_user() {
  local username=$1
  local groups=$2

  if getent passwd "$username" > /dev/null; then
    echo "User $username already exists" | tee -a $LOGFILE
  else
    useradd -m $username
    echo "Created user $username" | tee -a $LOGFILE
  fi

  # Add user to specified groups
  groups_array=($(echo $groups | tr "," "\n"))

  for group in "${groups_array[@]}"; do
    if ! getent group "$group" >/dev/null; then
      groupadd "$group"
      echo "Created group $group" | tee -a $LOGFILE
    fi
    usermod -aG "$group" "$username"
  done

  # Generate and set a random password for the user
  password=$(generate_random_password 12)
  echo "$username:$password" | chpasswd
  echo "$username,$password" >> $PASSWORD_FILE
  echo "Password for $username set" | tee -a $LOGFILE

  # Set permissions for the user's home directory
  chown "$username":"$username" "/home/$username"
  chmod 700 "/home/$username"
}

# Process each line in the input file
while IFS=';' read -r user groups; do
  user=$(echo "$user" | xargs)  # Trim whitespace
  groups=$(echo "$groups" | xargs)  # Trim whitespace
  create_user "$user" "$groups"
done < "$1"

echo "User creation process completed successfully." | tee -a $LOGFILE

Enter fullscreen mode Exit fullscreen mode

Log and Password File Locations:

LOGFILE="/var/log/user_management.log": Logs all actions.
PASSWORD_FILE="/var/secure/user_passwords.csv": Stores generated passwords securely.

Input File Check:
The script checks if an input file is provided and exits with an error message if not.

Directory and File Setup:
Necessary directories and files are created with appropriate permissions.

Random Password Generation:
The **generate_random_password** function creates a random password of a specified length (default is 12 characters).

User Creation Function:
The **create_user** function creates a user, assigns the user to specified groups, generates a random password, sets the password, and logs all actions.

Processing the Input File:
The script reads each line from the input file, extracts the username and groups, and calls the **create_user** function.

Running the Script
To run the script, use the following command:

nano create_users.sh
Enter fullscreen mode Exit fullscreen mode
chmod +x create_users.sh
Enter fullscreen mode Exit fullscreen mode

Logging and Password Storage
Log File: All actions are logged to /var/log/user_management.log.
Password File: Generated passwords are stored securely in /var/secure/user_passwords.csv with restricted access.
Error Handling
The script includes error handling to manage scenarios like existing users and missing input files gracefully. It provides clear documentation and comments within the code to ensure maintainability and readability.

At the end, the script logs a message indicating successful user creation and prompts users to review the LOG_FILE for detailed information on the operations performed.

Image description

Conclusion
By automating user management with this Bash script, you can streamline the onboarding process for new developers and maintain consistency in user account setups. For more information on automation and internships, visit HNG Internshipand HNG HIRE

Top comments (0)