Problem overview
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.
#!/bin/bash
# This resource is provided as a convenience for Level users. We cannot
# guarantee it will work in all environments. Please test before deploying
# to your production environment. We welcome contributions to our community
# library
# Level Library
# https://level.io/library/script-linux-delete-disable-users
# Define the list of users to disable/delete (replace with actual values)
USERS_TO_DELETE="{{UsersToDelete}}"
# Convert the comma-separated list into an array
IFS=',' read -r -a userArray <<< "$(echo "$USERS_TO_DELETE" | sed 's/, */,/g')"
for user in "${userArray[@]}"; do
# Trim spaces from the username
user=$(echo "$user" | xargs)
# Check if the user exists
if id "$user" &>/dev/null; then
# Disable the user by locking the account
sudo chage -E0 "$user"
echo "User $user has been disabled."
# Remove the user from the sudo (admin) group
# if groups "$user" | grep -q '\bsudo\b'; then
# sudo gpasswd -d "$user" sudo
# echo "User $user has been removed from the sudo group."
# fi
# Uncomment the next two lines to **delete** the user instead of just disabling
#sudo userdel -r "$user"
#echo "User $user has been deleted."
else
echo "User $user does not exist."
fi
done
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.
Use cases
- Automatically disabling accounts for recently offboarded employees
- Removing abandoned or dormant accounts discovered through periodic audits
- Responding in real time to security incidents or unauthorized user alerts
- Enforcing compliance mandates for least privilege or data security
Recommendations
- Pair this script with a script-based monitor in Level to disable suspicious or unapproved users on demand
- For scheduled enforcement, create a Level automation with a set trigger to routinely run the script
- Test the script on a non-production environment first to confirm proper functionality and results
- Uncomment the “userdel” line to permanently delete users once you’ve verified they’re truly unauthorized
- Check out the Admin Compliance & Remediation Automation