Problem overview
This script streamlines the process of identifying all active macOS user accounts with administrative privileges, cutting through complex manual checks and providing a concise overview of who truly has elevated permissions on any given machine.
#!/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-macos-get-local-admins
# Get all local admin users on macOS
admins=$(dscl . -read /Groups/admin GroupMembership | awk '{$1=""; print $0}' | xargs)
active_admins=()
for admin in $admins; do
if [[ -n "$admin" ]]; then
# Check if the account is expired
exp_date=$(dscl . -read /Users/"$admin" accountPolicyData 2>/dev/null | grep -A1 "accountExpires" | tail -1 | grep -oE '[0-9]{4}-[0-9]{2}-[0-9]{2}')
if [[ -z "$exp_date" || "$exp_date" > "$(date +%Y-%m-%d)" ]]; then
# Check if the account is locked
status=$(pwpolicy -u "$admin" -getpolicy 2>/dev/null | grep "isDisabled=1")
if [[ -z "$status" ]]; 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"
It inspects the admin group on macOS, filtering out users whose accounts are either locked or expired, and outputs a concise, comma-separated list of valid, active admins. By running under root-level permissions through Level, it eliminates the need for additional authentication steps and provides an authoritative snapshot of macOS admin access. This helps IT professionals and MSPs maintain a secure environment while meeting their compliance and auditing requirements.
Use cases
- Periodic security audits of macOS endpoints
- Spot checks for unauthorized admin access
- Identifying dormant but enabled macOS admin accounts
- Ensuring consistent compliance with least-privileged practices
Recommendations
- Configure a script-based monitor in Level to trigger this script on demand when suspicious privilege activity is detected
- Build an automation in Level with a schedule trigger to run regular, automated checks of macOS admin accounts
- Test the script in a non-production environment to verify its output before broad deployment
- Validate the results against your organization’s approved list of administrative accounts