Watch Demo×
×

See NinjaOne in action!

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

Automate DNS Cache Clearing in macOS: Full Script Guide

Key takeaways

  • Automates DNS cache clearing: The script efficiently clears DNS cache on macOS, automating a typically manual process.
  • User-friendly help function: Includes a print_help function for ease of use and better understanding.
  • Robust error handling: Features robust error handling through the die function, improving script reliability.
  • Command-line argument parsing: Parses user inputs to ensure correct script execution.
  • MacOS specific commands: Utilizes dscacheutil -flushcache and killall -HUP mDNSResponder, commands specific to macOS.
  • Enhances network performance: Regular flushing of DNS cache leads to improved network performance and connectivity.
  • Scalable solution: More scalable and efficient compared to manual flushing, especially in larger networks.
  • Safe and frequent use: Safe for frequent use, helping maintain up-to-date DNS information.
  • Versatile across MacOS versions: Compatible with various versions of macOS.
  • Augmented by IT management tools: Can be effectively paired with IT management platforms like NinjaOne for comprehensive network management.
  • Vital for dynamic networks: Particularly useful in environments with frequent DNS changes.

Introduction

Effective management of network resources is a cornerstone of IT operations. Among these, Domain Name System (DNS) cache plays a pivotal role, often impacting network performance and security. This blog explores a Bash script designed for macOS, which automates the process of flushing the DNS cache.

Background

DNS is like the phonebook of the internet, translating domain names into IP addresses. Over time, the DNS cache can become outdated or corrupted, leading to connection issues. IT professionals and Managed Service Providers (MSPs) routinely clear DNS caches to resolve these issues and ensure network integrity. This script is particularly valuable in environments where frequent changes to DNS records occur, such as dynamic cloud services or development stages.

The script:

#!/bin/bash

# Description: Clears the dns cache the number of times you specify (defaults to 3).
#
# Release Notes: Initial Release
# 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).
#
# Below are all the valid parameters for this script.
# Preset Parameter: "ReplaceWithNumberOfTimesToClearCache"
#
#

# Help text function for when invalid input is encountered
print_help() {
    printf '\n### Below are all the valid parameters for this script. ###\n'
    printf '\nPreset Parameter: "ReplaceWithNumberOfTimesToClearCache" \n'
    printf '\t%s\n' "The number of times you would like to clear the cache."
}

# Determines whether or not help text is nessessary and routes the output to stderr
die() {
    local _ret="${2:-1}"
    echo "$1" >&2
    test "${_PRINT_HELP:-no}" = yes && print_help >&2
    exit "${_ret}"
}

# Grabbing the parameters and parsing through them.
parse_commandline() {
    while test $# -gt 0; do
        _key="$1"
        case "$_key" in
        --*)
            _PRINT_HELP=yes die "FATAL ERROR: Got an unexpected argument '$1'" 1
            ;;
        *)
            if [[ -z $_arg_attempts ]]; then
                _arg_attempts=$1
            else
                _PRINT_HELP=yes die "FATAL ERROR: Got an unexpected argument '$1' but the number of attempts '$_arg_attempts' was already specified" 1
            fi
            ;;
        esac
        shift
    done
}

parse_commandline "$@"

# If the number of times isn't specified we should default to 3
if [[ -n $timesToClearCache ]]; then
    _arg_attempts=$timesToClearCache
fi

# If attempts was empty set a default
if [[ -z $_arg_attempts ]]; then
    _arg_attempts=3
fi

# Loop through each cache clearing attempt
for ((i = 1; i <= _arg_attempts; i++)); do
    sleep 1
    echo "DNS Cache clearing attempt $i."

    # Flushes the dns cache
    dscacheutil -flushcache
    killall -HUP mDNSResponder

    # Check if dscacheutil was successful
    if [ $? -ne 0 ]; then
        _PRINT_HELP=no die "FATAL ERROR: Failed to flush dns cache!" 1
    fi

    echo "Successfully cleared cache!"
    echo ""
done

 

Access over 300+ scripts in the NinjaOne Dojo

Get Access

Detailed breakdown

The script begins with a user-friendly help function, print_help, providing guidance on valid script parameters. This is crucial for ensuring users understand how to correctly utilize the script.

It then moves to die, a function that outputs error messages to standard error (stderr) and provides the help text if needed. This error handling is essential for diagnosing issues quickly.

The parse_commandline function follows, parsing through command-line arguments. If an unexpected argument is detected, it triggers an error message, enhancing script robustness by preventing invalid operations.

The core functionality is in the loop, which iterates based on the user-defined number of attempts to clear the DNS cache. For macOS, it utilizes dscacheutil -flushcache and killall -HUP mDNSResponder, both commands specific to macOS, to reset the DNS cache. Error checks after each flush ensure the operation was successful, with feedback provided to the user.

Potential use cases

Consider an IT admin in a company experiencing network issues after a DNS change. They could deploy this script to multiple Macs in the network, ensuring all machines have the updated DNS records, thus quickly resolving connectivity issues.

Comparisons

While manual flushing is possible, it’s time-consuming and prone to errors. Automated scripts like this provide a consistent and efficient alternative. Compared to GUI-based tools, scripts are more scalable, especially in larger networks.

FAQs

  • Will this script work on all macOS versions?
    • Yes, the commands used are standard across recent macOS versions.
  • Is it safe to run this script frequently?
    • Yes, flushing DNS cache is a safe operation and can be performed as needed.
  • Can this script be modified for other operating systems?
    • Yes, but the commands for flushing DNS cache will differ based on the OS.

Implications

Regularly flushing DNS cache can improve network performance and security. It ensures that the network connections are based on the most current DNS information, critical in fast-paced IT environments.

Recommendations

  • Schedule the script during low-traffic hours to minimize impact.
  • Regularly update the script to ensure compatibility with new macOS versions.
  • Monitor network performance post-execution to gauge the impact.

Final thoughts

Incorporating this script into the IT toolkit enhances efficiency and reliability in managing network resources. Tools like NinjaOne can complement such scripts by providing a comprehensive platform for IT management, offering oversight and control over diverse IT functions, crucial in today’s interconnected world.

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

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).