Linux User Creation With Bash Script

Introduction

Managing users and groups in a Unix-like operating system can be a tedious task, especially when dealing with multiple users. To simplify this process, we can use a Bash script to automate the creation of users and groups, set up home directories, generate random passwords, and log all actions. This blog post will walk you through a comprehensive Bash script that accomplishes these tasks.

Script Overview

The script we’re going to discuss performs the following functions:

  1. Create Users and Groups: Reads a file containing usernames and group names, creates the users and groups if they do not exist, and assigns users to the specified groups.

  2. Setup Home Directories: Sets up home directories with appropriate permissions and ownership for each user.

  3. Generate Random Passwords: Generates random passwords for the users and stores them securely.

  4. Log Actions: Logs all actions to /var/log/user_management.log for auditing and troubleshooting.

  5. Store Passwords Securely: Stores the generated passwords in /var/secure/user_passwords.csv with restricted access.

The Script

Here is the complete Bash script:

#!/bin/bash LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.csv" # Ensure /var/secure exists and has the correct permissions
mkdir -p /var/secure
chmod 700 /var/secure
touch "$PASSWORD_FILE"
chmod 600 "$PASSWORD_FILE" # Function to log messages
log_message() { echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
} # Function to generate random passwords
generate_password() { local password_length=12 tr -dc A-Za-z0-9 </dev/urandom | head -c $password_length
} # Function to add users, groups and set up home directories
setup_user() { local username=$1 local groups=$2 # Create the user if ! id -u "$username" &>/dev/null; then password=$(generate_password) useradd -m -s /bin/bash "$username" echo "$username:$password" | chpasswd log_message "User $username created." # Store the username and password echo "$username,$password" >> "$PASSWORD_FILE" log_message "Password for $username stored." else log_message "User $username already exists." fi # Create groups and add user to groups IFS=',' read -ra group_array <<< "$groups" for group in "${group_array[@]}"; do if ! getent group "$group" &>/dev/null; then groupadd "$group" log_message "Group $group created." fi usermod -aG "$group" "$username" log_message "Added $username to $group." done # Set up the home directory local home_dir="/home/$username" chown "$username":"$username" "$home_dir" chmod 700 "$home_dir" log_message "Home directory for $username set up with appropriate permissions."
} # Main script
if [ $# -eq 0 ]; then log_message "Usage: $0 <input_file>" exit 1
fi input_file=$1
log_message "Starting users and groups script." # Read the input file and process each line
while IFS=';' read -r username groups; do
setup_user "$username" "$groups"
done < "$input_file" log_message "Users created with password and set to groups script completed." 
Enter fullscreen mode
Exit fullscreen mode

Explanation

  1. Logging and Password File Setup: The script ensures that the /var/secure directory exists with the appropriate permissions. It creates the password file /var/secure/user_passwords.csv and sets

  2. permissions so that only the file owner can read it.
    Logging Function: The log_message function logs messages to /var/log/user_management.log with a timestamp, providing an audit trail of actions taken by the script.

  3. Password Generation Function: The generate_password function generates a random password of 12 characters, comprising uppercase and lowercase letters and digits.

  4. User Setup Function: The setup_user function creates a user if they do not already exist, generates and sets a password for them, creates groups if necessary, adds the user to the specified groups, and sets up their home directory with appropriate permissions.

  5. Main Script: The main part of the script reads an input file containing username;groups entries, processes each line, and calls the setup_user function for each user.

Usage

Prepare the Input File: Create a text file (e.g., input.txt) with the following format, where each line contains a username and a list of groups separated by a semicolon:

user1;group1,group2
user2;group3,group4
Enter fullscreen mode
Exit fullscreen mode

Run the Script: Save the script to a file (e.g., create_user.sh), Change the user to root sudo -s, make it executable, and run it with the path to your input file as an argument:

sudo -s
chmod +x create_user.sh
./create_user.sh input.txt
Enter fullscreen mode
Exit fullscreen mode

Note that running the script as a root user is necessary to ensure it has the required permissions to create users, modify groups, and write to the log and password files.

verify the script

 ~ cd /var/log/ ~ ls ~ user_management.log ~ cd /var/secure/ ~ ls ~ user_passwords.csv
Enter fullscreen mode
Exit fullscreen mode

Conclusion

This Bash script simplifies user management by automating the creation of users and groups, setting up home directories, generating random passwords, and logging all actions. By following the steps outlined above, you can efficiently manage user accounts on your system while maintaining security and a clear audit trail.

FOR TALENTS

HNG Internship
Hire Talents


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top