Back to Resources
Level
Script
Security
This script addresses the challenge of promptly and consistently managing user accounts on Linux systems by automatically disabling or removing those that are unauthorized, stale, or otherwise no longer needed. It helps reduce security vulnerabilities linked to overlooked or dormant accounts that retain unnecessary privileges.
The script references a “UsersToDelete” variable containing comma-separated usernames, then iterates through each to either disable or delete the corresponding user account on a Linux system. By default, it locks the accounts, preventing them from logging in, but you can uncomment specific lines to fully remove the user profiles and their home directories. Because it runs with root-level permissions through Level, you can incorporate it into script-based monitors that identify unauthorized users in real time or schedule regular compliance checks through Level automations.
1#!/bin/bash
2
3# This resource is provided as a convenience for Level users. We cannot
4# guarantee it will work in all environments. Please test before deploying
5# to your production environment. We welcome contributions to our community
6# library
7
8# Level Library
9# https://level.io/library/script-linux-delete-disable-users
10
11# Define the list of users to disable/delete (replace with actual values)
12USERS_TO_DELETE="{{UsersToDelete}}"
13
14# Convert the comma-separated list into an array
15IFS=',' read -r -a userArray <<< "$(echo "$USERS_TO_DELETE" | sed 's/, */,/g')"
16
17for user in "${userArray[@]}"; do
18 # Trim spaces from the username
19 user=$(echo "$user" | xargs)
20
21 # Check if the user exists
22 if id "$user" &>/dev/null; then
23 # Disable the user by locking the account
24 sudo chage -E0 "$user"
25 echo "User $user has been disabled."
26
27 # Remove the user from the sudo (admin) group
28 # if groups "$user" | grep -q '\bsudo\b'; then
29 # sudo gpasswd -d "$user" sudo
30 # echo "User $user has been removed from the sudo group."
31 # fi
32
33 # Uncomment the next two lines to **delete** the user instead of just disabling
34 #sudo userdel -r "$user"
35 #echo "User $user has been deleted."
36 else
37 echo "User $user does not exist."
38 fi
39done
40
41
Linux - Delete/Disable Users
This Bash script processes a comma-separated list of usernames provided through Level's script variables to perform account disablement on Linux systems. For each username in the list, it verifies the account exists, then disables it by setting the account expiration date to epoch 0 (with commented code available for removing sudo privileges or full account deletion). The script provides status messages for each attempted operation, indicating success or reporting if the specified user doesn't exist.
Bash
100
Local system
Explore more automations, scripts, and policies to further enhance your IT operations.