Author: Shubham Saini

Introduction

User account management is a frequent task for any system administrator or DevOps engineer. Whether you’re setting up new users, disabling inactive accounts, or just listing all users for an audit, the manual process can get repetitive. What if you could automate these tasks using a Bash script that performs user management with simple commands? In this guide, we’ll create a versatile Bash script that acts like a mini command-line tool for handling user accounts, adding some extra features to make it more interesting.

Why Automate User Management?

User management might seem straightforward, but in a busy environment, adding automation can save valuable time. Instead of using multiple commands to create, lock, or delete a user, our script will consolidate these tasks into a single command with different options. This way, you can manage your users more efficiently and avoid common mistakes.

Prerequisites

You’ll need:

  • Basic Bash Scripting Knowledge: If you’re familiar with basic Bash commands, you’re good to go!
  • Root Privileges: Most user management tasks need admin rights, so make sure you run the script as root or with sudo.

The Bash script will:

  • Create a New User: Prompt for additional details like shell and home directory.
  • Delete an Existing User: Optionally archive the user’s home directory before deletion.
  • List All Users: With extra filtering options to show only active or locked accounts.
  • Lock or Unlock a User Account: To control access.
  • Change a User’s Password: With an option to auto-generate a strong password.
  • Display Help and Usage Instructions.

The Enhanced Bash Script

Here’s our enhanced script, saved as user_manager.sh. This version adds more functionality and interactivity, making it useful for real-world administrative tasks.

    #!/bin/bash

    # User Management Bash Script
    # Author: Shubham
    # Version: 1.0
    # Date: 2024-10-17
    # Description: A Bash script to manage user accounts with options to create, delete, list, lock, unlock, and change user passwords.

    # Check if the script is run as root
    if [[ $EUID -ne 0 ]]; then
       echo "This script must be run as root" 
       exit 1
    fi

    # Function to display the usage of the script
    usage() {
        echo "Usage: $0 {create|delete|list|lock|unlock|passwd|help} [options]"
        echo "Commands:"
        echo "  create [username]      Create a new user (with optional shell and home dir)"
        echo "  delete [username]      Delete an existing user (with optional archive)"
        echo "  list                   List all users (with filter options)"
        echo "  lock [username]        Lock a user account"
        echo "  unlock [username]      Unlock a user account"
        echo "  passwd [username]      Change the password for a user (with auto-generate option)"
        echo "  help                   Show this help message"
        echo "Options for 'create':"
        echo "  --shell [shell]        Specify the shell (default: /bin/bash)"
        echo "  --home [dir]           Specify the home directory (default: /home/username)"
        echo "Options for 'delete':"
        echo "  --archive              Archive the user's home directory before deletion"
        echo "Options for 'list':"
        echo "  --active               Show only active users"
        echo "  --locked               Show only locked users"
    }

    # Function to create a new user
    create_user() {
        local username=$1
        shift
        local shell="/bin/bash"
        local home_dir="/home/$username"

        while [[ "$1" != "" ]]; do
            case $1 in
                --shell) shift; shell=$1 ;;
                --home)  shift; home_dir=$1 ;;
            esac
            shift
        done

        if id "$username" &>/dev/null; then
            echo "User '$username' already exists."
        else
            useradd -m -d "$home_dir" -s "$shell" "$username"
            if [[ $? -eq 0 ]]; then
                echo "User '$username' created successfully with shell $shell and home directory $home_dir."
            else
                echo "Failed to create user '$username'."
            fi
        fi
    }

    # Function to delete a user
    delete_user() {
        local username=$1
        shift
        local archive_home=false

        while [[ "$1" != "" ]]; do
            case $1 in
                --archive) archive_home=true ;;
            esac
            shift
        done

        if id "$username" &>/dev/null; then
            if [[ $archive_home == true ]]; then
                tar -czf "/tmp/${username}_home_backup.tar.gz" "/home/$username" &>/dev/null
                echo "User's home directory archived to /tmp/${username}_home_backup.tar.gz"
            fi
            userdel -r "$username"
            echo "User '$username' deleted successfully."
        else
            echo "User '$username' does not exist."
        fi
    }

    # Function to list all users with optional filters
    list_users() {
        local filter="all"

        if [[ "$1" == "--active" ]]; then
            filter="active"
        elif [[ "$1" == "--locked" ]]; then
            filter="locked"
        fi

        case $filter in
            active)
                awk -F':' '$7 !~ /nologin|false/ {print $1}' /etc/passwd
                ;;
            locked)
                passwd -S -a | awk '/LK/ {print $1}'
                ;;
            *)
                awk -F':' '{ print $1 }' /etc/passwd
                ;;
        esac
    }

    # Function to lock a user account
    lock_user() {
        local username=$1
        passwd -l "$username"
        echo "User '$username' has been locked."
    }

    # Function to unlock a user account
    unlock_user() {
        local username=$1
        passwd -u "$username"
        echo "User '$username' has been unlocked."
    }

    # Function to change user password
    change_password() {
        local username=$1
        if [[ "$2" == "--generate" ]]; then
            local new_password=$(openssl rand -base64 12)
            echo "$username:$new_password" | chpasswd
            echo "Password for '$username' has been changed to a new generated password: $new_password"
        else
            passwd "$username"
        fi
    }

    # Main script logic
    case "$1" in
        create)
            if [[ -n "$2" ]]; then
                create_user "$2" "${@:3}"
            else
                echo "Please provide a username."
                usage
            fi
            ;;
        delete)
            if [[ -n "$2" ]]; then
                delete_user "$2" "${@:3}"
            else
                echo "Please provide a username."
                usage
            fi
            ;;
        list)
            list_users "$2"
            ;;
        lock)
            if [[ -n "$2" ]]; then
                lock_user "$2"
            else
                echo "Please provide a username."
                usage
            fi
            ;;
        unlock)
            if [[ -n "$2" ]]; then
                unlock_user "$2"
            else
                echo "Please provide a username."
                usage
            fi
            ;;
        passwd)
            if [[ -n "$2" ]]; then
                change_password "$2" "$3"
            else
                echo "Please provide a username."
                usage
            fi
            ;;
        help|*)
            usage
            ;;
    esac

Key Features of the Enhanced Script

  • Create User with Options: You can now specify the shell and home directory for new users, making it suitable for various environments.
  • Delete User with Home Archiving: Before deleting a user, you have the option to archive the home directory, which is useful for data retention.
  • Advanced User Listing: Filter the list to show only active or locked users, perfect for audits.
  • Automatic Password Generation: When changing a user’s password, you can auto-generate a secure password.
  • Interactive Help: The usage function provides detailed instructions on using each feature.

Making the Script Executable

chmod +x user_manager.sh

Using the Enhanced Script

  1. Create a User with a Specific Shell:
sudo ./user_manager.sh create shubham --shell /bin/zsh --home /custom/home/shubham
  1. Delete a User and Archive Home Directory:
sudo ./user_manager.sh delete shubham --archive
  1. List Only Active Users:
sudo ./user_manager.sh list --active
  1. Change Password with Auto-Generation:
sudo ./user_manager.sh passwd shubham --generate

Conclusion

Automating user management tasks with a Bash script can transform tedious administrative duties into quick and effortless commands. The enhanced script not only simplifies account management but adds valuable features like automatic password generation and data archiving, making it an essential tool for any sysadmin’s toolkit.

With this script, you can spend more time on complex tasks and less on repetitive user management. Give it a try, and feel free to extend the script to include more advanced features, like group management or user expiration policies. Happy scripting!

Author: Shubham Saini

Categorized in:

Blog,