Technical Article: User Management Script with Enhanced Security
Published: 2024-07-02 14:40:58

This article explores a Bash script designed to automate user creation and management on Linux systems. It prioritizes security by utilizing secure file permissions and secure password storage.

**Learning More about HNG Internship**

This script can be a valuable tool for system administrators managing user accounts within organizations. To explore opportunities for such automation, consider checking out the HNG program [HNG](https://hng.tech/).

**Script Functionality**

The script takes a user file as input, where each line specifies a username and optionally, a comma-separated list of groups. Here's a breakdown of its key functionalities:

**Secure File Handling:**
Log file ($LOG_FILE (`LOG_FILE="/var/log/user_management.log"`)): is used to log actions performed by the script.
Password file ($PASSWORD_FILE (`PASSWORD_FILE="/var/secure/user_passwords.txt"`)): Stores usernames and randomly generated passwords with restricted permissions (chmod 600(`chmod 600 $PASSWORD_FILE`)).

**Password Generation Function:**

The generate_password function generates a 16-character random password using /dev/urandom (`generate_password() {< /dev/urandom tr -dc A-Za-z0-9 | head -c 16}`). 

**File Existence Check:**

The script checks if the user data file provided as an argument exists. If not, it exits with an error message.`if [ ! -f "$1" ]; then echo "User file not found! "exit 1 fi`

**Ensuring Log and Password Files:**

The script ensures that the log file and password file exist and sets appropriate permissions for security.
`touch $LOG_FILE
mkdir -p $(dirname $PASSWORD_FILE)
touch $PASSWORD_FILE
chmod 600 $PASSWORD_FILE`

**Reading and Processing User Data:**

The script reads the user data file line by line, expecting each line to contain a username and groups separated by a semicolon (;).
`while IFS=';' read -r username groups; do
    # Trim whitespace
    username=$(echo "$username" | xargs)
    groups=$(echo "$groups" | xargs)`

**Creating Users and Groups:**

For each user, the script:
Trims any leading or trailing whitespace.
`while IFS=';' read -r username groups; do
    # Trim whitespace
    username=$(echo "$username" | xargs)
    groups=$(echo "$groups" | xargs)`
Checks if the user already exists and skips if so.
`if id "$username" &>/dev/null; then
        echo "User $username already exists. Skipping..." | tee -a $LOG_FILE
        continue
    fi`
Creates the user with a home directory and the /bin/bash shell.
`useradd -m -s /bin/bash "$username"
    if [ $? -ne 0 ]; then
        echo "Failed to create user $username" | tee -a $LOG_FILE
        continue
    fi
`
Creates a personal group named after the user.
` groupadd "$username"`
Processes additional groups, sanitizes them to handle special characters, checks for their existence, and creates them if necessary.
`IFS=',' read -r -a group_array <<< "$groups"
    for group in "${group_array[@]}"; do
        group=$(echo "$group" | xargs)
        # Handle group names with special characters
        group=$(echo "$group" | sed 's/[^a-zA-Z0-9_-]//g')
        # Check if the group exists, if not create it
        if ! getent group "$group" > /dev/null; then
            groupadd "$group"
        fi`
Adds the user to the specified groups.
`# Add user to group
        usermod -aG "$group" "$username"
    done`


**Password Assignment:**

Generates a random password for each user and assigns it.
`password=$(generate_password) # Set the password for the user echo "$username:$password" | chpasswd`


**Logging Actions:**

Logs the creation of each user and their assigned groups.
`echo "Created user $username with groups $groups" | tee -a $LOG_FILE`

Stores the username and generated password in the secure password file.
`echo "$username:$password" >> $PASSWORD_FILE`

**Setting Permissions:**

Sets appropriate permissions on the log and password files for security.
`chmod 600 $PASSWORD_FILE
chmod 644 $LOG_FILE`

Here redirects you to my [GitHub](https://github.com/divine299/user-management-script/blob/ca3fac59d757e6332d549f89924aaa13bc551747/create_users.sh) page containing the entire code and its documentation 

**Conclusion**
This Bash script is a powerful tool for automating user management tasks on a Linux system. By reading user data from a file, it can create users, assign them to groups, and generate secure passwords efficiently. This script can save time and reduce the risk of errors compared to manual user management.

For more information on automating tasks and improving your DevOps skills, consider exploring the [HNG Internship Program](https://hng.tech/internship) and learn how you can hire top talent from their pool of skilled interns. The HNG Internship ([Premium](https://hng.tech/premium)) is an excellent opportunity for budding developers to gain real-world experience and for companies to find talented professionals.

This script is just one example of the kind of practical skills you can develop through programs like the HNG Internship. Happy automating!