DEV Community

chiemerie anaebo
chiemerie anaebo

Posted on

Optimising User Account Management on Linux Using a Bash Script

As a SysOps engineer, you often find yourself managing users and groups on Linux systems. This task can be tedious, especially when dealing with a large number of users. Automation is key to reducing manual workload and minimizing errors. In this article, I'll walk you through a Bash script that automates the process of creating and managing users and groups on a Linux system. This script is particularly useful for onboarding new developers and ensuring consistent user setups.

Why Automate User Management?

Manual user and group management can be time-consuming and prone to errors. Automating this process not only saves time but also ensures consistency and security. By using a script, you can:

  • Quickly create multiple users and groups.
  • Ensure home directories are properly set up with correct permissions.
  • Generate and securely store random passwords.
  • Log all actions for auditing purposes.

Prerequisites

The following are the requirements for creating and executing the script.

  • Fundamental Understanding of Linux Commands
  • Administrative privilege
  • Text editors such as Vim, Nano, and TextEdit

Script Overview

The script reads a text file containing usernames and group names, creates the users and groups as specified, sets up home directories, and logs all actions. Here’s a breakdown of the script:

Log File and Password File Definitions:
These lines specify the locations for the log and password files. The log file will record the script's activity, while the password file will safely store the produced passwords.

LOGFILE="/var/log/user_management.log"
PASSWORD_FILE="/var/secure/user_passwords.txt"

Enter fullscreen mode Exit fullscreen mode

Log Function:
This function logs messages to the log file with a timestamp.

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

Password Generation Function:
This function generates a random password using OpenSSL. The password is 12 characters long and encoded in base64.

generate_password() {
    openssl rand -base64 12
}
Enter fullscreen mode Exit fullscreen mode

Input File Check:
This block checks if the input file is provided as a command-line argument. If not, it displays a usage message and exits.

if [ "$#" -ne 1 ]; then
    echo "Usage: $0 <input_file>"
    exit 1
fi

Enter fullscreen mode Exit fullscreen mode

Create Secure Directory:
This block creates the /var/secure directory if it doesn't exist and sets its permissions to be accessible only by the owner.

mkdir -p /var/secure
chmod 700 /var/secure

Enter fullscreen mode Exit fullscreen mode

Read Input File Line by Line:
This block reads the input file line by line. It ignores empty lines and lines starting with #.

while IFS= read -r line || [ -n "$line" ]; do
    [[ -z "$line" || "$line" =~ ^# ]] && continue

Enter fullscreen mode Exit fullscreen mode

Parse Username and Groups:
This block splits each line into a username and groups using ; as the delimiter. It also trims any leading or trailing whitespace from the username.

IFS=';' read -r username groups <<< "$line"
username=$(echo "$username" | xargs)
Enter fullscreen mode Exit fullscreen mode

Check for Empty Username:
If the username is empty, the script skips to the next line.

[ -z "$username" ] && continue

Enter fullscreen mode Exit fullscreen mode

Create Group:
This block checks if a group with the same name as the username exists. If not, it creates the group and logs the action.

if ! getent group "$username" >/dev/null; then
    groupadd "$username"
    log "Created group $username"
fi
Enter fullscreen mode Exit fullscreen mode

Create User:
This block checks if the user exists. If not, it creates the user with a home directory, assigns the user to their personal group, sets the password, stores the password, and logs the action.

if ! id -u "$username" >/dev/null 2>&1; then
    password=$(generate_password)
    useradd -m -g "$username" "$username"
    echo "$username:$password" | chpasswd
    echo "$username:$password" >> $PASSWORD_FILE
    log "Created user $username with password"
else
    log "User $username already exists"
fi
Enter fullscreen mode Exit fullscreen mode

Assign User to Additional Groups:
This block splits the groups string into an array using , as the delimiter, trims whitespace from each group name, creates any additional groups if they don't exist, and assigns the user to these groups.

IFS=',' read -r -a group_array <<< "$groups"
for group in "${group_array[@]}"; do
    group=$(echo "$group" | xargs)
    [ -z "$group" ] && continue

    if ! getent group "$group" >/dev/null; then
        groupadd "$group"
        log "Created group $group"
    fi

    usermod -aG "$group" "$username"
    log "Added $username to group $group"
done

Enter fullscreen mode Exit fullscreen mode

Final Log Message:
This line logs the completion of the user and group creation process.

log "User and group creation process completed."

Enter fullscreen mode Exit fullscreen mode

Conclusion

Automating user and group management on Linux systems can greatly improve efficiency and reduce errors. The script provides a robust solution for onboarding new developers and ensuring consistent user setups.

Interested in honing your technical skills and working on real-world projects? Check out the HNG Internship for opportunities to learn and grow. If you're looking to hire talented interns, explore the HNG Hire page.

By incorporating automation into your workflow, you can streamline repetitive tasks and focus on more strategic initiatives. Happy scripting!

Top comments (0)