DEV Community

Cover image for Linux users creation with Bash script
Adesokan Israel
Adesokan Israel

Posted on

Linux users creation with Bash script

Introduction

In a growing organization, managing user accounts efficiently is crucial. Automating the process can save significant time and reduce errors. This article explains a Bash script designed to read a list of users and groups from a text file, create the users and groups, set up home directories, generate passwords, and log all actions. This script is particularly useful for SysOps engineers responsible for maintaining system user accounts.

Image description

The purpose of this blog is to provide solution for the creation of Linux users using bash script in an automated and reliable way. Below is the scenario for the problem statement.
Your company has employed many new developers. As a SysOps engineer, write a bash script called create_users.sh that reads a text file containing the employee’s usernames and group names, where each line is formatted as user;groups.
The script creates users and groups as specified, set up home directories with appropriate permissions and ownership, generate random passwords for the users, and log all actions to /var/log/user_management.log. Additionally, store the generated passwords securely in /var/secure/user_passwords.txt.

Script Overview

The create_users.sh script reads a text file where each line is formatted as user;groups, creates the users and groups, sets up home directories, and generates random passwords. Actions are logged to /var/log/user_management.log, and passwords are securely stored in /var/secure/user_passwords.csv.

Detailed Breakdown

Log and Secure Password File Setup:
The script begins by setting up the log file and secure password file. It ensures that the directories exist and sets appropriate permissions for the password file.

LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.csv"

mkdir -p /var/log
touch $LOG_FILE

mkdir -p /var/secure
touch $PASSWORD_FILE
chmod 600 $PASSWORD_FILE
Enter fullscreen mode Exit fullscreen mode

Logging Function:
A function is defined to log messages with timestamps.

log_message() {
    echo "$(date +'%Y-%m-%d %H:%M:%S') - $1" >> $LOG_FILE
}
Enter fullscreen mode Exit fullscreen mode

Password Generation

A helper function generates random passwords.

generate_password() {
    tr -dc A-Za-z0-9 </dev/urandom | head -c 12
}
Enter fullscreen mode Exit fullscreen mode
  • Input File Check

The script checks if an input file is provided and exits if not.

if [ -z "$1" ]; then
    echo "Usage: $0 <user-file>"
    exit 1
fi

USER_FILE="$1"
Enter fullscreen mode Exit fullscreen mode
  • Processing the Input File

The script reads the input file line by line, ignoring whitespace and empty lines, and processes each user.

while IFS=';' read -r username groups; do
    username=$(echo $username | xargs)
    groups=$(echo $groups | xargs)
    [ -z "$username" ] && continue
Enter fullscreen mode Exit fullscreen mode
  • Creating Users and Groups

For each user, the script checks if the user already exists, creates the primary group (same as the username), creates the user, sets up home directory permissions, and generates a password.

if id -u "$username" >/dev/null 2>&1; then
    log_message "User $username already exists"
else
    groupadd "$username"
    log_message "Group $username created"

    useradd -m -g "$username" -s /bin/bash "$username"
    log_message "User $username created with home directory /home/$username"

    chmod 700 "/home/$username"
    log_message "Set permissions for /home/$username"

    password=$(generate_password)
    echo "$username:$password" | chpasswd
    log_message "Password set for user $username"

    echo "$username,$password" >> $PASSWORD_FILE
fi
Enter fullscreen mode Exit fullscreen mode
  • Adding Users to Additional Groups

The script then adds the user to any additional groups specified in the input file.

if [ -n "$groups" ]; then
    IFS=',' read -ra GROUP_ARRAY <<< "$groups"
    for group in "${GROUP_ARRAY[@]}"; do
        group=$(echo $group | xargs)
        if ! getent group "$group" >/dev/null; then
            groupadd "$group"
            log_message "Group $group created"
        fi
        usermod -aG "$group" "$username"
        log_message "User $username added to group $group"
    done
fi
Enter fullscreen mode Exit fullscreen mode

Completion

Finally, the script logs the completion of the user creation process.

"log_message "User creation process completed"

echo "User creation process completed. Check the log file at $LOG_FILE for details."

Image description

To run and test the create_users.sh script, follow these steps:

Step 1:

Prepare Your Environment

Ensure you have the necessary permissions to create users, groups, and modify system files. Running the script might require superuser privileges.

Step 2:

Create the Input File

Create a text file with the usernames and groups. For example, create a file named users.txt with the following content:

isreal;sudo,dev,www-data
isreal2;sudo
isreal3;dev,www-data
Enter fullscreen mode Exit fullscreen mode

Step 3:

Ensure Necessary Directories Exist

Ensure that the directories /var/log and /var/secure exist and have the appropriate permissions. You might need to create them if they don't exist:

sudo mkdir -p /var/log /var/secure
sudo touch /var/log/user_management.log /var/secure/user_passwords.csv
sudo chmod 600 /var/secure/user_passwords.csv
Enter fullscreen mode Exit fullscreen mode

Step 4:

Run the Script

To execute the script, use the following command, passing the name of the input file as an argument:

sudo bash create_users.sh users.txt
Enter fullscreen mode Exit fullscreen mode

Step 5:

Verify the Script's Actions

Check the Log File: Verify the actions logged in /var/log/user_management.log.

sudo cat /var/log/user_management.log
Enter fullscreen mode Exit fullscreen mode

Check the Passwords File: Verify the securely stored passwords in /var/secure/user_passwords.csv.

sudo cat /var/secure/user_passwords.csv
Enter fullscreen mode Exit fullscreen mode

Verify User and Group Creation: Check if the users and groups were created correctly.

List users and groups

getent passwd | grep -E 'isreal|isreal2|isreal3'
getent group | grep -E 'isreal|sudo|dev|www-data'
Enter fullscreen mode Exit fullscreen mode

Check Home Directory Permissions:

Ensure the home directories were created with the correct permissions.

ls -ld /home/isreal /home/isreal2 /home/isreal3
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

Image description

Image description

Image description

Conclusion

With this, we have successfully automated user creation with a Bash script which could help to reduce errorand ensure reliability, from defining user details in users.txt to execution, the project has transitioned from execution to completion.
To be part of the program that provided this task scenario, visit their official websites to gain more insights

https://hng.tech/internship

https://hng.tech/hire

Thanks for reading

Top comments (0)