DEV Community

Cover image for User and Group Management in Linux
Emmanuel Omoiya
Emmanuel Omoiya

Posted on

User and Group Management in Linux

In recent times where organizations and companies hold secrets of the biggest magnitude e.g. proprietary secrets, trademark secrets e.t.c. and store them on the main company network (server), adding employees to that network or server has to be done with high accuracy and precision by assigning the employee to the appropriate groups according to his/her job title in order to protect this secret of the company and to make sure no one has access to such information except certain people like, the C.E.O, C.T.O, C.M.O. e.t.c.

Today, we're going to look into such phenomenon taking Linux (Ubuntu distro) as our case study environment.

How are we going to implement this you may ask?

Well, we're going to create a bash script that takes the path to a .txt file as our input file which contains the names of employees and the groups you wish to place them in.

For example

alice; developers, foodies
bob; testers; admins
Enter fullscreen mode Exit fullscreen mode

This .txt file contains lines in the format of user;groups delimited by a comma"

Before going into the code, we must first know and understand what we want our code to do explicitly

  • Read users in format user; groups
  • Create users and groups as specified
  • setup home directories with appropriate permissions and ownership
  • generate random passwords for the users
  • store the generated passwords securely in /var/secure/user_passwords.txt
  • log all actions to /var/log/user_management.log Note: handle error scenarios like existing users

Preparatory steps

  • Create a file named create_users.sh in your home directory on linux
touch create_users.sh
Enter fullscreen mode Exit fullscreen mode
  • Open this file with nano editor to add your code
nano create_users.sh
Enter fullscreen mode Exit fullscreen mode

Now let's follow through with how we want our script to run.

Step 1

Define the following paths in which you want to save your logs and users password

LOG_FILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.txt"
Enter fullscreen mode Exit fullscreen mode

Step 2

Ensure the directory exists and has the appropriate permissions

if [ ! -d "/var/secure" ]; then
    mkdir -p /var/secure
    chmod 700 /var/secure
fi
Enter fullscreen mode Exit fullscreen mode

Step 3

Ensure the log file and password file exist and are writable

touch $LOG_FILE $PASSWORD_FILE
chmod 600 $PASSWORD_FILE
chmod 644 $LOG_FILE
Enter fullscreen mode Exit fullscreen mode

Step 4

Add the function to log all user actions and include a timestamp to each respective action

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

Step 5

Check if the script is run as root

if [ "$EUID" -ne 0 ]; then
    log "Script must be run as root."
    echo "Please run as root."
    exit 1
fi
Enter fullscreen mode Exit fullscreen mode

Step 6

Check if the input file is provided and readable

if [ ! -f "$1" ]; then
    log "Input file not provided or does not exist."
    echo "Usage: $0 <input_file>"
    exit 1
fi
Enter fullscreen mode Exit fullscreen mode

Step 7

Add the function to generate user passwords

generate_password(){
    < /dev/urandom tr -dc 'A-Za-z0-9!@#$%^&*()_+' | head -c 8
}
Enter fullscreen mode Exit fullscreen mode

Step 8

Read the input file line by line

while IFS=';' read -r user groups;
do
    user=$(echo "$user" | xargs) # Trim whitespace
    groups=$(echo "$groups" | xargs) # Trim whitespace

    if id "$user" &>/dev/null; then
        log "User $user already exists."
        echo "User $user already exists. Skipping."
        continue
    fi
Enter fullscreen mode Exit fullscreen mode

Add the following codes to the while do block

Step 9

Create groups if they do not exist and collect them in a list

    IFS=',' read -ra group_list <<< "$groups"
    group_string=""
    for group in "${group_list[@]}"; do
        group=$(echo "$group" | xargs)  # Trim whitespace
        if ! getent group "$group" &>/dev/null; then
            groupadd "$group"
            log "Group $group created."
        else
            log "Group $group already exists."
        fi
        group_string+="$group,"
    done
    group_string=${group_string%,} # Remove trailing comma
Enter fullscreen mode Exit fullscreen mode

Step 10

Create user and assign to groups

    useradd -m -G "$group_string" "$user"
    if [ $? -eq 0 ]; then
        log "User $user created and added to groups $groups"
    else
        log "Failed to create user $user."
        echo "Failed to create user $user. Check log for details."
        continue
    fi
Enter fullscreen mode Exit fullscreen mode

Step 11

Generate and assign a password

    password=$(generate_password)
    echo "$user:$password" | chpasswd
    if [ $? -eq 0 ]; then
        log "Password set for user $user."
    else
        log "Failed to set password for user $user."
        echo "Failed to set password for user $user. Check logs for details."
        continue
    fi
Enter fullscreen mode Exit fullscreen mode

Step 12

Store the password securely

    echo "$user:$password" >> $PASSWORD_FILE
    log "Password for user $user stored securely."
Enter fullscreen mode Exit fullscreen mode

Step 13

Set ownership and permissions for home directory

    chown "$user:$user" "/home/$user"
    chmod 700 "/home/$user"
    log "Home directory for user $user set up with appropriate permissions."
Enter fullscreen mode Exit fullscreen mode

Last Step

Close the while do block and log the end

done < "$1"

log "Users - groups creation process completed."
echo "User creation process completed. Check $LOG_FILE for details."
Enter fullscreen mode Exit fullscreen mode

With this code you can be sure to add your respective employees to the appropriate Groups and add permissions, in order for your organization top secret information doesn't get into the wrong hands 😊.

Thanks for following me through with this article.

A big shout out to HNG, HNG Internship, HNG Hiring for inspiring this article.

Reach out to me on Linkedin or X(Twitter) if you want to have a nice chat about anything and I mean absolutely anything.

Top comments (0)