Delete User account
  • 10 Oct 2024
  • 1 Minute to read
  • PDF

Delete User account

  • PDF

Article summary

Use this script to delete a user account on Linux machines.

  1. Copy and save the contents below to a UTF-8 editor like notepad++ OR Sublime Text in Windows or gedit in Ubuntu.

    1. If you are using notepad++ then use the bottom right panel to change the type to Unix (LF).

  2. Or click here to download the file.

    #!/bin/bash
    
    # Define variables
    username="ENTER_USER_NAME"
    hostname="ENTER_USER_HOSTNAME"
    
    # Function to check if the user is logged in
    is_user_logged_in() {
        who | grep -q "^$1 "
    }
    
    # Function to kill all processes associated with the user
    kill_user_processes() {
        pkill -u "$1"
    }
    
    # Check if hostname is present
    if grep -q "$hostname" /etc/passwd; then
        # Check if user is present
        if id "$username" &>/dev/null; then
            # Check if the user is logged in
            if is_user_logged_in "$username"; then
                echo "User $username is currently logged in. Attempting to log them out..."
                kill_user_processes "$username"
                sleep 2  # Wait for processes to terminate
                if is_user_logged_in "$username"; then
                    echo "Failed to log out user $username. Aborting deletion."
                    exit 1
                else
                    echo "User $username has been logged out."
                fi
            fi
            
            # Delete user account
            sudo userdel --force "$username"
            echo "User $username has been deleted."
        else
            echo "$username has been deleted."
        fi
    else
        echo "Hostname $hostname not found. Exiting..."
        exit 1
    fi
  3. In the script, replace the following placeholder:

    1. Provide the username and hostname of the user whose account you want to unlock.
      # Define variables

      username="ENTER_USER_NAME"

      hostname="ENTER_USER_HOSTNAME"

  4. Follow our guide to upload & publish the script using Scalefusion Dashboard.

Note:

  1. Some of the scripts and their contents are sourced from internet and yes, our new friend ChatGPT.

  2. Please validate the scripts on a test machine before deploying them on all your managed devices.

  3. Scalefusion has tested these scripts, however Scalefusion will not be responsible for any loss of data or system malfunction that may arise due to the usage of these scripts.


Was this article helpful?