Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Automating User Creation with a Bash Script
Precious Ogundipe
Precious Ogundipe

Posted on

Automating User Creation with a Bash Script

As a DevOps Engineer, writing automation scripts is an essential part of your job. These scripts help streamline repetitive tasks and increase efficiency. In this task, we must create a bash script that reads a text file containing employees' usernames and group names, where each line is formatted asuser; groups. The script must create the specified users and groups, set up home directories with the appropriate permissions and ownership, generate random passwords for each user, and log all actions to/var/log/user_management.log. Additionally, it should securely store the generated passwords in/var/secure/user_passwords.txt and implement error handling to manage scenarios where users already exist, all while providing clear documentation and comments within the script.

Requirements

  • Linux Machine
  • Bash Script

Steps

sudo nano create_users.sh
Enter fullscreen modeExit fullscreen mode
  • creates a file to write the script
#!/bin/bash# Ensure script is run as rootif [[ $EUID -ne 0 ]]; then    echo "This script must be run as root" >&2    exit 1fi# Check if input file is providedif [[ -z "$1" ]]; then    echo "Usage: $0 <user-list-file>"    exit 1fiUSER_FILE="$1"LOG_FILE="/var/log/user_management.log"PASSWORD_FILE="/var/secure/user_passwords.csv"# Ensure log and password directories existmkdir -p /var/securetouch "$LOG_FILE" "$PASSWORD_FILE"chmod 600 "$PASSWORD_FILE" # Process each line in the filewhile IFS=';' read -r username groups; do    username=$(echo "$username" | xargs)      groups=$(echo "$groups" | xargs)      # Skip empty lines    [[ -z "$username" ]] && continue    # Creates groups if it doesn't exist    if ! getent group "$username" >/dev/null; then        groupadd "$username"        echo "Created group: $username" | tee -a "$LOG_FILE"    fi    # Creates a user with and adds them to their group    if ! id "$username" &>/dev/null; then        useradd -m -g "$username" -s /bin/bash "$username"        echo "Created user: $username" | tee -a "$LOG_FILE"    else        echo "User $username already exists, skipping..." | tee -a "$LOG_FILE"        continue    fi    # Assign users to additional groups    if [[ -n "$groups" ]]; then        IFS=',' read -ra GROUPS_ARRAY <<< "$groups"        for group in "${GROUPS_ARRAY[@]}"; do            group=$(echo "$group" | xargs)              if ! getent group "$group" >/dev/null; then                groupadd "$group"                echo "Created group: $group" | tee -a "$LOG_FILE"            fi            usermod -aG "$group" "$username"            echo "Added $username to group: $group" | tee -a "$LOG_FILE"        done    fi    # Generate a random password    password=$(openssl rand -base64 8)    echo "$username,$password" >> "$PASSWORD_FILE"    echo "Generated password for $username" | tee -a "$LOG_FILE"    # Set password    echo "$username:$password" | chpasswddone < "$USER_FILE"echo "User creation process completed." | tee -a "$LOG_FILE"exit 0
Enter fullscreen modeExit fullscreen mode
  • explaining each section of the bash script
#!/bin/bash
Enter fullscreen modeExit fullscreen mode
  • This section specifies that the script should be executed using the Bash shell
if [[ $EUID -ne 0 ]]; then    echo "This script must be run as root" >&2    exit 1fi
Enter fullscreen modeExit fullscreen mode
  • This section ensures the script is executed with root privileges. Without root, actions like creating users and groups will fail.
if [[ -z "$1" ]]; then    echo "Usage: $0 <user-list-file>"    exit 1fi
Enter fullscreen modeExit fullscreen mode
  • This section, verifies that the user provided the input file which contains the usernames and groups.
USER_FILE="$1"LOG_FILE="/var/log/user_management.log"PASSWORD_FILE="/var/secure/user_passwords.csv"mkdir -p /var/securetouch "$LOG_FILE" "$PASSWORD_FILE"chmod 600 "$PASSWORD_FILE"
Enter fullscreen modeExit fullscreen mode

This section sets file paths for the input file, log file, and password file, creates necessary directories and files, and sets secure permissions on the password file.

while IFS=';' read -r username groups; do    username=$(echo "$username" | xargs)      groups=$(echo "$groups" | xargs)          # Skip empty lines    [[ -z "$username" ]] && continue
Enter fullscreen modeExit fullscreen mode
  • This section reads the input file line by line, using; as a delimiter to separate the username from the groups, and trims any extra whitespace.
    if ! getent group "$username" >/dev/null; then        groupadd "$username"        echo "Created group: $username" | tee -a "$LOG_FILE"    fi
Enter fullscreen modeExit fullscreen mode
  • This section checks if a group with the same name as the username exists. If not, it creates the group and logs the action.
    if ! id "$username" &>/dev/null; then        useradd -m -g "$username" -s /bin/bash "$username"        echo "Created user: $username" | tee -a "$LOG_FILE"    else        echo "User $username already exists, skipping..." | tee -a "$LOG_FILE"        continue    fi
Enter fullscreen modeExit fullscreen mode
  • This section creates the user with the home directory, assigning them to their group. If the user already exists, it displays a message that the user already exists and skips further processing for that user.
    if [[ -n "$groups" ]]; then        IFS=',' read -ra GROUPS_ARRAY <<< "$groups"        for group in "${GROUPS_ARRAY[@]}"; do            group=$(echo "$group" | xargs)             if ! getent group "$group" >/dev/null; then                groupadd "$group"                echo "Created group: $group" | tee -a "$LOG_FILE"            fi            usermod -aG "$group" "$username"            echo "Added $username to group: $group" | tee -a "$LOG_FILE"        done    fi
Enter fullscreen modeExit fullscreen mode
  • This section processes additional groups by splitting the string on commas, creates them if they don't exist, adds the user to each, and logs the operations
    password=$(openssl rand -base64 12)    echo "$username,$password" >> "$PASSWORD_FILE"    echo "Generated password for $username" | tee -a "$LOG_FILE"    # Set password    echo "$username:$password" | chpasswd
Enter fullscreen modeExit fullscreen mode
  • This section generates a secure random password, appends the username and password to the secure password file, and sets the generated password for the user.
echo "User creation process completed." | tee -a "$LOG_FILE"exit 0
Enter fullscreen modeExit fullscreen mode
  • This section logs a message that the process is finished and exits the script successfully.
sudo nano users.txt
Enter fullscreen modeExit fullscreen mode
  • This command helps opens a file where the script will be written.
light; sudo,dev,www-dataidimma; sudomayowa; dev,www-datajohn; admin,devemma; sudo,www-dataalice; devbob; admin,sudocharlie; www-datadave; dev,admineve; sudo
Enter fullscreen modeExit fullscreen mode
  • Input this in the file
sudo bash create_users.sh users.txt
Enter fullscreen modeExit fullscreen mode
  • Use this command to run the script

bash script loading

sudo cat /var/log/user_management.logsudo cat /var/secure/user_passwords.csv
Enter fullscreen modeExit fullscreen mode
  • Use this command to view the content of the files created to ensure the script worked

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

DevOps Engineer
  • Location
    Lagos, Nigeria
  • Pronouns
    Her/She
  • Joined

More fromPrecious Ogundipe

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp