How to Wipe a Mac Hard Drive Remotely with a Bash Script

As an IT professional or a Managed Service Provider (MSP), the task of managing user accounts on a network of Mac computers can be quite challenging. Imagine needing to repurpose a device, troubleshoot extensive issues, or ensure sensitive data is completely removed—these are daunting tasks that could require a significant amount of time and resources. This is where the ‘Wipe a Mac Hard Drive Remotely’ bash script comes into play. Today, we’re going to delve into how this powerful bash script can improve your IT operations.

Introducing the ‘Wipe a Mac Hard Drive Remotely’ Bash Script

This bash script is not just a tool—it’s a potent solution designed to handle some of the most challenging situations in IT management. Its primary function? To wipe a Mac hard drive remotely. But it offers more than that—it provides granular control, enabling IT professionals to preserve certain user accounts while eliminating others.

#!/usr/bin/env bash
# Description: Remove all users and their data.
#
# Release Notes: Initial Release
# (c) 2023 NinjaOne
#   By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
#   Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
#   Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
#   Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
#   Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
#   Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
#   Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
#   EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#
# Usage: <url> <download file path> [expected md5 sum]
# <> are required
# [] are optional
# Example: https://www.nirsoft.net/utils/advancedrun.zip /tmp/advancedrun.zip
#  Downloads advancedrun.zip
# Example: https://www.nirsoft.net/utils/advancedrun.zip /tmp/advancedrun.zip 1f0913135878bb6cd30c1f3f6cf4b882
#  Downloads advancedrun.zip, verify's the provided md5 summed hash
#
# Notes: If the path doesn't exist this script will create the folders needed to place it there.
#  If you used /tmp/MyFiles/advancedrun.zip and the MyFiles folder didn't exist then it would create it.
#  The same for /tmp/MyFiles/Tools/advancedrun.zip, it would create MyFiles and Tools.
#
# To exclude users from being removed, specify each user as a parameter.
# Usage:
# [user1] [user2] ... [userN]
# Example:
# Admin HelpDesk Bob

# store arguments in a special array
args=("$@")
# get number of elements
USER_COUNT=${#args[@]}

# Print out list of user and count the number of users
EXCLUDED_USERS=("${args[*]}")
echo "User that will be excluded: ${EXCLUDED_USERS[*]}"

# List all users that should be under /Users/
USERS=("$(dscacheutil -q user | grep -A 3 -B 2 -e uid: 5'[0-9][0-9]' | grep -E "^name: " | awk '{print $2}')")
# Don't filter out user if we don't have a list to exclude
if ((0 == USER_COUNT)); then
    USER_LIST=("${USERS[@]}")
    # We have decided to not exclude any users
    # Remove the .AppleSetupDone file so that on reboot we prompt to create a new first user
    rm -rf "/var/db/.AppleSetupDone"
else
    # Filter out users that we want to exclude
    USER_LIST=()
    while IFS='' read -r line; do USER_LIST+=("$line"); done < <(echo "${USERS[@]}" "${EXCLUDED_USERS[@]}" | tr ' ' 'n' | sort | uniq -u)
fi

# Remove users from system, along with their data.
for USER in "${USER_LIST[@]}"; do
    echo "Removing user: ${USER}"
    echo "Running: dscl . -delete "/Users/${USER}""
    dscl . -delete "/Users/${USER}"
    status=$?
    # Output result
    # If status is 0 and USER is not an empty string and /Users/${USER} is a folder
    if [ $status -eq 0 ]; then
        echo "Removed ${USER} from login"
        if [ -n "${USER}" ] && [ -d "/Users/${USER}" ]; then
            # Double quote prevent spaces from breaking things,
            #  even though user names should never have spaces in them
            # ${} around a variable prevent globbing: https://tldp.org/LDP/abs/html/globbingref.html
            rm -rf "/Users/${USER}"
            rmStatus=$?
            [ $rmStatus -eq 0 ] && echo "Removed /Users/${USER}" || echo "Failed to remove /Users/${USER}"
        else
            echo "Folder /Users/${USER} is not a folder or doesn't exist"
        fi
    else
        echo "Failed to remove ${USER} from login"
    fi
done
# Wait 1 minute so we can report back
echo "Rebooting in 1 minute."
echo "If this computer doesn't reboot, manual rebooting might be needed."
shutdown -r +2
osascript -e 'tell app "System Events" to restart'

Diving Deep: How the ‘Wipe a Mac Hard Drive Remotely’ Script Works

The script operates by identifying and deleting user accounts on a Mac, effectively removing all associated data. To accomplish this, it utilizes the `dscl` command, a directory service command-line utility native to macOS. This command allows you to create, read, and manage Directory Service data.

Here’s the exciting part: You can specify user accounts that the script should exclude from the wipe operation. This means you can keep your admin or helpdesk accounts intact while removing all others—a feature that’s crucial when you need to wipe a Mac hard drive remotely but still maintain control over the system.

Moreover, the script takes care of the `.AppleSetupDone` file. When this file is removed, the Mac triggers the setup process to create a new user upon the next startup. This is an essential step in regaining control over the system post-wipe.

Finally, the script issues a reboot command, restarting the system and sealing all changes made.

Potential Applications

This script has a multitude of applications, making it an essential tool in the arsenal of an IT professional or MSP. Here are some scenarios where this script shines:

  1. Device Repurposing: Quickly reset a machine to its initial setup state, perfect for when a device needs to be assigned to a new user.
  2. Troubleshooting: In situations where extensive issues have made a user profile unstable, a complete wipe might be the quickest solution.
  3. Data Security: When a user’s tenure ends or a device is retiring, the script can ensure sensitive data does not fall into the wrong hands by completely removing user data.

Security Implications: Safeguarding Data

As powerful as the script is, it’s crucial to consider the security implications. The script is designed to delete data—so once executed, the data is gone for good. Therefore, it’s imperative always to have a backup of any necessary data before running the script. Always remember the golden rule in IT: data not backed up is data considered lost.

Furthermore, this tool should only be used responsibly and within the purview of your permissions. Unauthorized use of such tools can lead to serious legal repercussions.

Final Thoughts

In the fast-paced world of IT, tools like this script are not just convenient—they’re a necessity. This bash script allows you to wipe a Mac hard drive remotely, saving time, and ensuring robust data security. In the grand scheme of IT management, it’s resources like these that can make a world of difference.

Remember, with great power comes great responsibility. Always ensure you have the necessary permissions and backups before executing any operations that can lead to data loss. The ‘Wipe a Mac Hard Drive Remotely’ is a powerful tool, but it should always be used with careful consideration.

When managing Mac user accounts remotely, NinjaOne can serve as an invaluable tool. As a cloud-based remote monitoring and management platform, NinjaOne seamlessly supports scripts like the ‘Wipe a Mac Hard Drive Remotely’. Not only does it allow for efficient execution of the script across many devices, but it also provides robust tracking and reporting features. This means IT professionals and MSPs can execute the script, monitor its progress, and document its results all within a single platform. As such, NinjaOne can greatly enhance the ease and effectiveness of using scripts like this one in large-scale IT environments

You may be asking, “What about wiping a Windows hard drive?” and we’ve got you covered. Check out our blog post on “How to Wipe a Windows Hard Drive with PowerShell“.

Try this script on NinjaOne.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

Watch Demo×
×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).