User and Group Management in Linux

RMAG news

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

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

Open this file with nano editor to add your code

nano create_users.sh

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”

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

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

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
}

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

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

Step 7

Add the function to generate user passwords

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

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

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

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

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

Step 12

Store the password securely

echo $user:$password >> $PASSWORD_FILE
log “Password for user $user stored securely.”

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.”

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.”

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.