unable to delete Non ADMIN or AD users using shell script

raghdasi
New Contributor III

Hello All,

We have fleet of laptops that we give them to students for short term (1 day to one month) and after we get them back our support staff suppose to login to them and delete the students account. I am trying to come up with a script so support staff can just double click on it and delete the accounts expect the local admin that I created. For some reason even when I am running the script as root it is giving error "Operation not permitted" I even try to change the ownership before deletion and that didn't work either.

I appreciate your feedback. This script will be used in MacOS Mojave 10.14.5 or later

Regards,
Ramin

This is the script:

#!/bin/sh
username1="mgsadmin"
username2="Admin"
username3="libadmin"

####################################################################################################
# SCRIPT OPERATIONS -  - REALLY!!! - DO NOT MODIFY BELOW THIS LINE
####################################################################################################
RESULT=""
for U in /Users/*; do 
    if [ -d "$U" ]; then
        if [ "$U" == "/Users/Shared" ] || [ "$U" == "/Users/Guest" ]; then
            /bin/echo "Found $U, ignored"
            USERNAME=`/bin/echo $U | tr '/' ' ' | awk '{print $NF}'`
            RESULT=`echo "$RESULT$USERNAME-IGNORED "`
        else
            /bin/echo "Found $U, continuing..."
            USERNAME=`/bin/echo $U | tr '/' ' ' | awk '{print $NF}'`
            /bin/echo "Parsed username as: $USERNAME"
            ADMINCHECK=`/usr/bin/dsmemberutil checkmembership -U $USERNAME -G admin | awk '{print $3}'`
            if [ "$ADMINCHECK" == "not" ]; then
                if [ "$USERNAME" == "$username1" ] || [ "$USERNAME" == "$username2" ] || [ "$USERNAME" == "$username3" ] || [ "$USERNAME" == "$username4" ]; then
                    /bin/echo "$USERNAME is on the exempt list, ignoring..."
                    RESULT=`echo "$RESULT$USERNAME-EXEMPT "`
                else    
                    /bin/echo "$USERNAME not an Admin nor exempt, taking action..."
                    RESULT=`echo "$RESULT$USERNAME-Action Taken "`
                    chflags -f -R nouchg $U
                    /bin/echo "Forcing the removal of $U" && sudo /bin/rm -Rf $U
                fi
            else
                /bin/echo "$USERNAME was found to be a Local Admin, ignoring"
                RESULT=`echo "$RESULT$USERNAME-ADMIN "`
            fi
        fi
    fi
done
echo ""
echo "============================================================"
echo "Summary: $RESULT"
echo "============================================================"
1 REPLY 1

Mauricio
Contributor III

Due to the new macOS security/SIP that will not be allowed (Operation not permitted output)
You will need sysadminctl command for that.

#!/bin/sh
sysadminctl -deleteUser <user name> -adminUser <administrator user name> -adminPassword <administrator password>