How to Setup Users and User Groups on Linux
Tags: linux, sysops, devops, bash
Published: 2024-07-03 10:38:07

Setting up users and user groups is the first step to managing employees in your organisation. As a SysOps engineer one of the basic tools you must familiarise yourself with is linux and its environment. Its important that when creating users for your organisation you must properly configure what access and how each user interface within the organisation, their access, groups and permissions; All these can be done on your machine in a linux environment using a script.

## Linux User and User Group Creation

In this article, I will be showing you a step by step process on how you can setup users and configure specific user groups they should belong.

## Prerequisites
Before we begin, make sure you have the following installed and ready to use:

1. **A Virtual machine** - VM running on [**Linux**](https://www.linux.org/) environment, I recommend [**Ubuntu**](https://ubuntu.com/).
2. Basic understanding of linux commands.
3. **A code editor**, I use [**Visual Studio Code**](https://code.visualstudio.com/).

## Step 1: Create user file
Specify a file where your users will be listed and the groups they should belong to. I recommend a simple output for this, so that it can be easy to identify. For this tutorial, we will be using a sample file users.txt, and its formatted as **users;groups**.

Example:

```
soji;sudo,dev,www-data
ade;sudo,dev
ayo;dev
```

In the example above, the word before the semicolon represents the `user` and after represents the `group(s)`.

In line one above, `soji` is the **user** and `sudo,dev,www-data` are the **user groups** to be created and assigned to the user; Similarly for line two **user** is `ade`, with groups `sudo,dev`.

## Step 2: Create script file
Open your code editor and create file, e.g `create_users.sh`, you can also create the file using your terminal by running: 

```
touch create_users.sh
```

_**Your script file will handle the actual logic of what will be done to `users.txt`**_.

The thought process around this is to run a command for example:

```
bash create_users.sh users.txt 
```

Which will be used to create users and groups.

## Step 3: Script Implementation
First we need to check that a first argument is passed and if not should return an error and then exit the program.

**Check if first argument is passed:**

```
if [[ ! $1 ]]; then
echo "Error: requires at least one arg to be passed, e.g bash create_users.sh <name-of-text-file>"
exit 1
fi
```

Then, we need to be able to allow our script know when we pass `user.txt` and then process it, and to go about this we check if `users.txt` is passed.

**Note:** _The name of the file doesn't matter, but that its a file and type is of `text/plain` which is the `mime-type` for text files._

**Check if file exists:**

```
if [ ! -f $1 ]
then
    echo "Error: file does not exists"
    exit 1
fi
```

**Check if file type is `text/plain`:**

```
if [[ ${1##*.} != "txt" && "$(file -b --mime-type "$1")" != "text/plain" ]]
then
  echo "Error: required file type is text"
  exit 1
fi
```

The next thing is we will need to read through each line of the `users.txt` file.

**Read line by line of users.txt:**

```
# Read the FILE
while IFS= read -r line || [ -n "$line" ]; 
do

# Assign variable for <user>
username=$(printf "%s" "$line"| cut -d \; -f 1)

# Assign variable for <groups>
usergroups=$(printf "%s" "$line"| cut -d \; -f 2)

echo "----- Start process for: '$username' -----"

# Create user
create_user $username

# Create user groups
for group in ${usergroups//,/ } ; do 
    create_group $group
    add_user_to_group $username $group
done

echo "----- Done with '$username' -----"
echo ""
done < $1
```

In the above code block, here we read each line of `users.txt` file, and extract the `username` and `user groups`, having done this it is easy for us to create the user and groups.

It contains the following functions:

- **create_user**
- **create_group**
- **add_user_to_group**

I have broken down each functions below.

**Create user: `create_user`**
I created a function my in script implementation named `create_user`.
Functions are good for easier code readability and clean code structure, also helps to reuse a certain logic in different sections of your code or scripts.

```
create_user() {
    username=$1
    password=$(gen_random_password)

    # If username exists, do nothing
    if [ ! $(cat /etc/passwd | grep -w $username) ]; then
        # Create the user with the specified username
        # 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_data_path

        create_file_in_directory $dir

        save_user_data $username $password $dir
        
        # Set file group to user and give read only acces
        sudo chgrp $username $dir
        sudo chmod 040 $dir
    fi
}
```

A user is created from the above code block, we assign a password to the user, so they always have access their account and directory.

**`gen_random_password` function is used to generate random password for the user**

```
gen_random_password() {
    < /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c12
}
```

After user and password is created, I then stored the user password on the user directory, I used the path a path:

**`[user home directory]/var/secure/user_passwords.txt`**

for user with name `soji`, its saved at:

**`/home/soji/var/secure/user_passwords.txt`**

Only the user is set to have access to it and its a `read only file`.


**Create group: `create_group`**
We then need to assign the user to the usergroups passed in the users.txt file, but first we need to create the groups.

If group already exists, the code block does nothing, this help for proper error handling.

```
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`:**
When the group is created we assign user to the created group

```
add_user_to_group() {
    #  Add user to group
   sudo usermod -aG $2 $1
   msg="'$1' added to '$2'"
   echo $msg
   log $msg
}
```

**Log function `log`:**
I used this to log all the actions by passing the log data/message. Logs where logged into `/var/log/user_management.log`

```
log() {
    sudo printf "$*\n" >> $log_path
}
```

**Thats all!!!**

_**Note: One thing you will observe is how I did some error handling in the script, this is important to avoid errors when you run your script.**_

## Step 4: Run script file
Now its time to test our script.
Run file by using the command below on your terminal, make sure you are the the correct path/directory where the files exists.

```
bash create_users.sh users.txt
```

**Script OK?** you should see result:

```
File and path created: /var/log/user_management.log
----- Start process for: 'soji' -----
User 'soji' created with the password '*******'
File and path created: /home/soji/var/secure/user_passwords.txt
Group created 'sudo'
'soji' added to 'sudo'
Group created 'dev'
'soji' added to 'dev'
'soji' added to 'www-data'
----- Done with 'soji' -----

----- Start process for: 'ade' -----
User 'ade' created with the password '*******'
File and path created: /home/ade/var/secure/user_passwords.txt
'ade' added to 'sudo'
'ade' added to 'dev'
----- Done with 'ade' -----

----- Start process for: 'ayo' -----
User 'ayo' created with the password '*******'
File and path created: /home/ayo/var/secure/user_passwords.txt
'ayo' added to 'dev'
----- Done with 'ayo' -----
```


**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 is available on Github: [Linux user creation code](https://github.com/sodiadrhain/linux-user-creation)**


## HNG Internships
Looking for ways to improve and develop you skills with world class talents, check out **[HNG Internship website](https://hng.tech/internship).**

If you want to hire world class freelancers and developers, check:  **[Hire from HNG](https://hng.tech/hire)**

## Conclusion 
Setting up users and user groups with linux is a pretty straight forward process that allows you to specify the actions you ant to perform. By taking these steps, you can easily create users in your environment and attach them to different groups.

**Happy SysOps(ing).**