Problem overview
This script addresses the need for a straightforward way to identify which Linux user accounts have elevated privileges through the sudo group while confirming that those accounts are neither locked nor expired. This helps ensure only valid and active users maintain admin-level access, enhancing security oversight.
#!/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-get-local-admins
# Get all users in the 'sudo' group (local admins)
admins=$(getent group sudo | cut -d: -f4 | tr ',' '\n')
active_admins=()
for admin in $admins; do
if [[ -n "$admin" ]]; then
# Check if the account is expired
exp_date=$(sudo chage -l "$admin" | grep "Account expires" | awk -F': ' '{print $2}')
if [[ "$exp_date" == "never" || "$exp_date" == "" ]]; then
# Check if the account is locked
status=$(sudo passwd -S "$admin" | awk '{print $2}')
if [[ "$status" != "L" ]]; then
active_admins+=("$admin")
fi
fi
fi
done
# Convert array to comma-separated string
detectedAdmins=$(IFS=','; echo "${active_admins[*]}")
# Output active admins for verification
echo "$detectedAdmins" This script checks each user in the sudo group to confirm whether the account is still valid and active, filtering out any locked or expired profiles. By returning a concise list of legitimate local admins, it removes the guesswork in managing privileged access on Linux systems. Administrators can use this data to maintain a secure environment, responding quickly to any unauthorized privilege assignments or stale accounts that should be removed.
Use cases
- Validating current sudo users on Linux endpoints
- Conducting routine security checks or compliance audits
- Verifying locked or expired account statuses for privileged users
- Quickly filtering out inactive or invalid admin accounts
Recommendations
- Set up a script-based monitor in Level to run this script on demand when you suspect unauthorized changes to sudo privileges. See Admin Compliance Automation and Admin Users Monitor.
- Consider scheduling routine checks by creating a Level automation with a scheduled trigger, enabling regular audits of local admin accounts.
- Always test the script in a non-production environment before deploying to production.
- Review and validate the output against known organizational policies for managing privileged accounts.