Creating and Managing Users and Groups on Linux with Bash Scripts: An Efficient Guide 🚀🐧
Tags: devops, cloudcomputing, ubuntu, bash
Published: 2024-07-05 03:38:01

Welcome to Linux user management! In a growing organization, manually managing user accounts and groups can quickly become tedious and error-prone. To streamline this process and maintain security and productivity, automation is key. 🛠️💪

With a Bash script, you can automate the repetitive tasks of creating and managing users and groups, ensuring consistency and efficiency while saving countless hours and reducing the risk of errors.

In this article, we’ll show you how to create a script to automate the user and group creation process—a common task for any SysOps engineer. Let's dive in and simplify your workflow! 🌟

## **Prerequisites**

1. Linux or Ubuntu running on either VM (Virtual box), Docker, AWS Ec2 instance.
2. Basic knowledge of Linux commands and Bash scripting.
3. Root privileges to execute the script.
4. Basic understanding of shell scripting and user management in Linux


**Step 1: Create user file** 
Create a `.txt `file where your users will be listed and the groups they should be added to. A simple and easy to read file will be recommended. For this article , a sample file `user.txt` has been created and will be formatted as `user;groups`

Example 

```
Gabriel;sudo,dev,www-data
Sultan;sudo
Chelsea;dev,www-data
```
The first line in the example above `Gabriel` is the user and groups are `sudo, dev, www-data`.

**Step 2: Create script file** 
Open your code editor and create a file e.g `create_users.sh`, this can also be created in your root directory using your terminal by running:

```
touch create_users.sh 
```
_NB: The script file created will handle the logic of the user and group in_ **Step 1**

**Step 3: Script implementation**
First we need to check the administrative priviledge of the script user.

Check if the first argument is passed: 

- The script begins with a shebang line and a check for root privileges to ensure the necessary permissions for user and group management.
```
#!/bin/bash
 if (( "$UID != 0" ))
then
    echo "Error: script requires root privilege"
exit 1
fi

```
**Shebang (#!/bin/bash)**: Indicates that the script should be run in the Bash shell.
**Root Privileges Check**: Verifies if the script is executed by the root user. If not, it prints an error and exits.

Then , the script processes input arguments and checks for the presence and type of the file `(text/plain)` containing user data.

```
# Save all arguments in an array
ARGS=("$@")

# Check whether no arguments are supplied
if [ "$#" -eq 0 ]; then
    echo "No arguments supplied"
    exit 1
fi

# Define a variable for the file
FILE=${ARGS[0]}

# Check if the file exists
if [ ! -f "$FILE" ]; then
    echo "Error: File $FILE does not exist."
    exit 1
fi

# Get the MIME type and check if it is text/plain
file_type=$(file -b --mime-type "$FILE")
if [[ "$file_type" != "text/plain" ]]; then
    echo "Error: required file type is not text/plain"
    exit 1 
fi

```
**Argument Handling**: Captures script arguments and checks if any are provided.
**File Existence Check**: Verifies if the specified file exists.
**MIME Type Check**: Ensures the file is a plain text file.

**Logging and Data Writing Functions**
I used this function below to log all actions by logging all user actions into `/var/log/user_management.log`

```
# Logging and writing data
log() {
    sudo printf "$*\n" >> $log_path
}

# Function to save user data
user_data() {
    sudo printf "$1,$2\n" >> $3
}

```
**Generate Random Passwords**
`genpasswd` function is used to generate a secure random password of specified length (default 16 characters)for the user.

```
genpasswd() { 
	local l=$1
       	[ "$l" == "" ] && l=16
      	tr -dc A-Za-z0-9_ < /dev/urandom | head -c ${l} | xargs 
}
```

**Process Each Line in the users.txt file:** 
The below code block will read each line of `users.txt` file and get the `username` and `user groups `.

```
# Create user function

    create_user(){
        username="$1"
        password=$(genpasswd)
 # If username exists, do nothing
    if [ ! $(cat /etc/passwd | grep -w $username) ]; then

        # User is created with a group as their name
        sudo useradd -m -s /bin/bash $username
 # Set the user's password
        echo "$username:$password" | sudo chpasswd
        msg="User '$username' created with the password '********'"
        echo $msg
        log $msg

       # Save user data
        dir=/home/$username/$user_pass
        create_file_directory $dir
        user_data $username $password $dir

         # Set file group to user and give read only access
        sudo chgrp $username $dir
        sudo chmod 640 $dir
    fi

    }

create_group() {
    # Create group
    # If group exists, do nothing
    if [ ! $(cat /etc/group | grep -w $1) ]; then
        sudo groupadd $1
        msg="Group created '$1'"
        echo $msg
        log $msg
    fi
}

 #  Add user to group
    add_user_to_group() {

   sudo usermod -aG $2 $1
   msg="'$1' added to '$2'"
   echo $msg
   log $msg
}

```
The code block above contains the following functions: 
`create_user Function`: Creates a user with a home directory and sets the password.
`create_group Function`: Creates a group if it doesn’t already exist.
`add_user_to_group Function`: Adds a user to a specified group.

The user and password is created and then the details are then stored in the user directory using the below path: 
`[user home directory]/var/secure/user_passwords.txt`

The user data reads file and creates users and groups accordingly.

```
# Read the FILE
while IFS= read -r line || [ -n "$line" ]; do
    username=$(printf "%s" "$line" | cut -d ';' -f 1)
    echo "----- Process started for: '$username' -----"
    create_user $username
    usergroups=$(printf "%s" "$line" | cut -d ';' -f 2)
    for group in ${usergroups//,/ } ; do 
        create_group $group
        add_user_to_group $username $group
    done
    echo "----- Process Done with '$username' -----"
done < $FILE

```

**Step 4: Run script file**

It's time to test our script to ensure that our code is working.

Run the `.txt` file by using the command below on your terminal.

```
bash create_users.sh users.txt
```
The below result should be displayed:

```
File and path created: /var/log/user_management.log
----- Process started for: 'Gabriel' -----
User 'Gabriel' created with the password '********'
File and path created: /home/Gabriel/var/secure/user_passwords.txt
'Gabriel' added to 'sudo'
'Gabriel' added to 'dev'
'Gabriel' added to 'www-data'
----- Process Done with 'Gabriel' -----
----- Process started for: 'Sultan' -----
User 'Sultan' created with the password '********'
File and path created: /home/Sultan/var/secure/user_passwords.txt
'Sultan' added to 'sudo'
----- Process Done with 'Sultan' -----
----- Process started for: 'Chelsea' -----
User 'Chelsea' created with the password '********'
File and path created: /home/Chelsea/var/secure/user_passwords.txt
'Chelsea' added to 'dev'
'Chelsea' added to 'www-data'
----- Process Done with 'Chelsea' -----
root@32cb601ed360:~# cat /home/Gabriel/var/secure/user_passwords.txt
Gabriel,yDEoSe1RfzIwxmhk
root@32cb601ed360:~# bash create.users.sh users.txt
File and path created: /var/log/user_management.log
----- Process started for: 'Gabriel' -----
'Gabriel' added to 'sudo'
'Gabriel' added to 'dev'
'Gabriel' added to 'www-data'
----- Process Done with 'Gabriel' -----
----- Process started for: 'Sultan' -----
'Sultan' added to 'sudo'
----- Process Done with 'Sultan' -----
----- Process started for: 'Chelsea' -----
'Chelsea' added to 'dev'
'Chelsea' added to 'www-data'
----- Process Done with 'Chelsea' -----
```

**To see all groups created run:**

```
sudo cat /etc/group
```
**To see all users and groups they belong run:**

```
sudo cat /etc/passwd 
```

My full code implementation can be found on Github: [Creating and Managing Users](https://github.com/Adeshile2/user-manage-bash)

**HNG Internships**
For more information about the HNG Internship, visit [HNG Internship (https://hng.tech/internship) and if you want to hire world class freelancers and developers , check: [HNG Hire](hng.tech/hire).

Thanks for reading through please do ensure to leave feedback so as to better serve my reader 😊

**Conclusion**
This Bash script automates the process of creating and managing users and groups on a Linux system, making it easier to maintain consistency and security across your user base. By following this guide, you can efficiently manage user accounts and group memberships with minimal manual effort.