Create a User Management Script

Summary: Add, delete, and lock users from a script.


Managing users is a common and crucial task for system administrators. While interactive commands like adduser, userdel, and passwd are effective, automating these tasks with a script can save time, reduce errors, and enhance security. In this article, you'll learn how to create a user management script in Bash that allows you to add, delete, and lock user accounts from the command line.


Prerequisites

  • Root access: Creating, deleting, or modifying users requires administrative privileges.
  • Bash shell: This guide uses Bash scripting, standard on most Linux distributions.
  • Familiarity with Linux commands: Understanding useradd, userdel, and passwd is helpful.

Script Overview

Our script will handle the following tasks:

  • Add a user: Optionally set a password and create a home directory.
  • Delete a user: Remove the user account and optionally the home directory.
  • Lock a user: Prevent the user from logging in.

We'll use positional arguments to specify the task and the username.


The Script

Here's a sample script named user_manage.sh:

#!/bin/bash

show_help() {
    echo "Usage: $0 [add|delete|lock] username [password]"
    echo ""
    echo "  add     username [password]   - Add user with optional password"
    echo "  delete  username              - Delete user and remove home directory"
    echo "  lock    username              - Lock user account"
    exit 1
}

# Ensure the script is run as root
if [ "$EUID" -ne 0 ]; then
    echo "Please run as root."
    exit 1
fi

if [ $# -lt 2 ]; then
    show_help
fi

ACTION="$1"
USERNAME="$2"
PASSWORD="$3"

case "$ACTION" in
    add)
        if id "$USERNAME" &>/dev/null; then
            echo "User '$USERNAME' already exists."
            exit 1
        fi
        useradd -m "$USERNAME"
        if [ $? -eq 0 ]; then
            echo "User '$USERNAME' created."
            if [ -n "$PASSWORD" ]; then
                echo "$USERNAME:$PASSWORD" | chpasswd
                echo "Password set for '$USERNAME'."
            else
                echo "No password set. User cannot log in without a password."
            fi
        else
            echo "Failed to create user."
            exit 1
        fi
        ;;
    delete)
        if id "$USERNAME" &>/dev/null; then
            userdel -r "$USERNAME"
            if [ $? -eq 0 ]; then
                echo "User '$USERNAME' deleted."
            else
                echo "Failed to delete user '$USERNAME'."
                exit 1
            fi
        else
            echo "User '$USERNAME' does not exist."
            exit 1
        fi
        ;;
    lock)
        if id "$USERNAME" &>/dev/null; then
            passwd -l "$USERNAME"
            if [ $? -eq 0 ]; then
                echo "User '$USERNAME' locked."
            else
                echo "Failed to lock user '$USERNAME'."
                exit 1
            fi
        else
            echo "User '$USERNAME' does not exist."
            exit 1
        fi
        ;;
    *)
        show_help
        ;;
esac

How the Script Works

  1. Safety Checks:
    • Ensures the script is run as root.
    • Requires at least two arguments (an action and a username).
  2. Add User:
    • Checks if the user exists.
    • Creates a home directory and sets a password (if provided).
  3. Delete User:
    • Removes the user and their home directory.
  4. Lock User:
    • Disables the account by locking the password.

Usage Examples

Make the script executable:

chmod +x user_manage.sh
  • Add a new user with a password:

    sudo ./user_manage.sh add alice StrongPass1!
    
  • Add a user without a password:

    sudo ./user_manage.sh add bob
    
  • Delete a user and their home directory:

    sudo ./user_manage.sh delete alice
    
  • Lock a user account:

    sudo ./user_manage.sh lock bob
    

Important Notes

  • Security: Setting passwords on the command line can expose them in shell history or process lists. For production environments, consider alternative secure methods for setting passwords.
  • User Data: Deleting a user with -r removes their home directory and files. Ensure backups if needed.
  • Error Handling: The script outputs errors if an action fails, but you can enhance error handling for larger environments.

Conclusion

Automating user management through a script simplifies administrative tasks and ensures consistent operations across systems. By customizing and expanding upon this script, you can further automate tasks like batch user management, reporting, and integrating with system monitoring.

For more advanced management, consider learning about configuration management tools like Ansible or Salt, which offer scalable user and system administration.


Want more scripting tutorials? Leave a comment or check our Linux Scripting category for the latest guides!