Watch Demo×
×

See NinjaOne in action!

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

Script Guide: Automated Local Hostname & Computer Renaming for macOS

Key takeaways

  • Automated efficiency: The script automates the renaming of Mac’s computer and local hostnames, enhancing efficiency in network management.
  • User-friendly vs. network names: It distinguishes between the user-friendly computer name and the network-visible local hostname.
  • Parameter flexibility: Users can choose to rename either the local hostname, the computer name, or both.
  • Strict validation rules: The script enforces naming standards, ensuring compliance with hostname conventions.
  • Error management: Robust error handling provides clear feedback and prevents common pitfalls.
  • DNS cache flushing: It includes a step to flush the DNS cache, facilitating immediate network recognition of changes.
  • DHCP renewal dependency: Changes in names may not fully propagate until the next DHCP renewal cycle.
  • Automation vs. manual process: The script offers a significant efficiency improvement over the manual renaming process.
  • Security and clarity: Encourages maintaining a naming convention that supports network security and clarity.
  • Integration with management tools: The script’s functionality exemplifies the type of automation that can be integrated into IT management systems like NinjaOne.

Changing a Mac’s computer name and local hostname is a crucial task for IT professionals managing multiple devices across a network. Efficiently renaming these components can streamline network management and simplify device identification, ensuring seamless operation in dynamic IT environments.

Background

The provided Bash script offers a robust solution for renaming a Mac’s computer name and local hostname. These elements are pivotal in a network setup: the computer name is the user-friendly identifier visible in Finder, while the local hostname is used within the network. This script is particularly useful for IT professionals and Managed Service Providers (MSPs) who need to manage device identities consistently and efficiently.

The script:

#!/bin/bash

# Description: Change's both the mac's computername (friendly name seen in Finder) and local hostname (what you would see in the network). Please note the hostname will update upon the next dhcp renewal.
#
# 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 only the new computer name is required!
# Preset Parameter: "ReplaceWithNewComputerName" --localhostname-only --computername-only
# --localhostname-only: Sets only the LocalHostName (The one you see when scanning the network)
# --computername-only: Sets only the user-friendly ComputerName (The one you see in finder)

# Help text function for when invalid input is encountered
print_help() {
  printf '\n### Below are all the (case sensitive) valid parameters for this script only the new computer name is required! ###\n'
  printf '\nPreset Parameter: "ReplaceWithNewComputerName" --localhostname-only --computername-only \n'
  printf '\t%s\n' "--localhostname-only: Sets only the LocalHostName (The one you see when scanning the network)"
  printf '\t%s\n' "--computername-only: Sets only the user-friendly ComputerName (The one you see in finder)"
}

# 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}"
}

# THE DEFAULTS INITIALIZATION - OPTIONALS
_arg_localhostname_only="off"
_arg_computername_only="off"
_typical="on"

# Grabbing the parameters and parsing through them.
parse_commandline() {
  while test $# -gt 0; do
    _key="$1"
    case "$_key" in
    --localhostname-only)
      _arg_localhostname_only="on"
      _typical="off"
      ;;
    --computername-only)
      _arg_computername_only="on"
      _typical="off"
      ;;
    --*)
      _PRINT_HELP=yes die "FATAL ERROR: Got an unexpected argument '$1'" 1
      ;;
    *)
      if [[ -z $_arg_name ]]; then
        _arg_name=$1
      else
        _PRINT_HELP=yes die "FATAL ERROR: Got an unexpected argument '$1' but the new computername '$_arg_name' was already specified" 1
      fi
      ;;
    esac
    shift
  done
}

# Dtermines if the hostname is valid.
validate_localhostname() {
  pattern=" |'"
  if [[ $1 =~ $pattern ]]; then
    _PRINT_HELP=yes die "FATAL ERROR: Local Hostnames DO NOT support spaces or most special characters - is okay!" 1
  fi

  if [[ ${#1} -gt 253 ]]; then
    _PRINT_HELP=yes die "FATAL ERROR: Local Hostnames cannot be more than 253 characters long!" 1
  fi

  if [[ ${#1} -gt 15 ]]; then
    printf "\nWARNING: Hostname is longer than 15 characters!"
    printf "\tWhile technically osx will let you set a hostname of basically any length you may experience issues if the name is absurdly long."
  fi
}

# Initializes parameter processing
parse_commandline "$@"

if [[ -n $newName ]]; then
  _arg_name=$newName
fi

if [[ -n $action ]]; then
  if [[ $action == "Change Local Host Name Only" ]]; then
    _arg_localhostname_only="on"
    _typical="off"
  fi
  if [[ $action == "Change Computer Name Only" ]]; then
    _arg_computername_only="on"
    _typical="off"
  fi
fi

# If they didn't give me a new name I should error out
if [[ -z $_arg_name ]]; then
  _PRINT_HELP=yes die 'FATAL ERROR: No Computer Name was given! Please enter in the new name in the "Preset Parameter" box in Ninja! For Example "MyNewName".' 1
fi

# If they didn't specify which of the 2 names to change we'll change both
if [[ $_typical == "on" ]]; then
  validate_localhostname "$_arg_name"
  echo "Changing both LocalHostName and ComputerName to $_arg_name..."

  # This actually changes the name
  scutil --set LocalHostName "$_arg_name"
  # Sleeps for a few seconds as scutil sometimes takes a second or two for the new name to appear
  sleep 7
  # Tests that the change was successful
  new_localhostname=$(scutil --get LocalHostName)
  if [[ $new_localhostname != "$_arg_name" ]]; then
    _PRINT_HELP=no die "FATAL ERROR: failed to set local hostname to $_arg_name." 1
  else
    echo "Success!"
  fi

  # Changes the friendly name
  scutil --set ComputerName "$_arg_name"
  # Sleeps for a few seconds as we're gonna test immediately afterwards
  sleep 7
  # Test that we were successful
  new_computername=$(scutil --get ComputerName)
  if [[ $new_localhostname != "$_arg_name" ]]; then
    _PRINT_HELP=no die "FATAL ERROR: failed to set Computer Name to $_arg_name." 1
  else
    echo "Success!"
  fi

fi

# This is the same as above just localhostname only
if [[ $_arg_localhostname_only == "on" ]]; then
  validate_localhostname "$_arg_name"
  echo "Changing LocalHostName to $_arg_name..."
  scutil --set LocalHostName "$_arg_name"
  sleep 7
  new_localhostname=$(scutil --get LocalHostName)
  if [[ $new_localhostname != "$_arg_name" ]]; then
    _PRINT_HELP=no die "FATAL ERROR: failed to set local hostname to $_arg_name." 1
  else
    echo "Success!"
  fi
fi

# Same as above just friendly name only
if [[ $_arg_computername_only == "on" ]]; then
  echo "Changing ComputerName to $_arg_name..."
  scutil --set ComputerName "$_arg_name"
  sleep 7
  new_computername=$(scutil --get ComputerName)
  if [[ $new_computername != "$_arg_name" ]]; then
    _PRINT_HELP=no die "FATAL ERROR: failed to set Computer Name to $_arg_name." 1
  else
    echo "Success"
  fi
fi

# Flushes the dns cache so that the mac is prepared to start handing out its new name
dscacheutil -flushcache

# Warns the user that it will take some time for the new name to show up
printf "\nWARNING: The devicename in Ninja will likely display the old name until the next dhcp renewal."
printf "\n\tOSX determines its devicename\hostname from the dhcp or dns server."
printf "\n\tTypically these services will update their records upon receiving a new DHCP request from the device."

 

Access 300+ scripts in the NinjaOne Dojo

Get Access

Detailed breakdown

The script operates in several key stages:

  • Parameter handling: It begins by parsing command-line arguments, allowing users to specify whether they want to change the local hostname, the computer name, or both.
  • Validation: It includes a validation function to ensure the new name conforms to hostname standards, checking for prohibited characters and length restrictions.
  • Name changing: The scutil command is used to apply the new names. After each change, the script pauses briefly, ensuring the system recognizes the new name before proceeding.
  • Error handling: The script robustly manages errors, providing clear feedback in case of issues.
  • DNS cache flushing: Finally, it flushes the DNS cache, ensuring that the new names are immediately recognized across the network.
  • User notification: The script concludes by reminding the user that changes might not be visible until the next DHCP renewal.

Potential use cases

Imagine an IT professional at a school needs to rename Macs in a computer lab for easier management. By using this script, they can efficiently update each machine’s identity, ensuring a consistent naming convention across the network.

Comparisons

Traditionally, renaming a Mac requires manual intervention through System Preferences, which is time-consuming and prone to errors. This script automates the process, reducing the likelihood of mistakes and saving significant time.

FAQs

  • How do I use this script?
    • Simply run the script with the new name as an argument, optionally specifying which name type to change.
  • Can I rename a machine to a name with special characters?
    • No, the script validates the name to ensure it’s compliant with hostname standards.
  • Will the changes be instant?
    • The script flushes the DNS cache, but some changes may only appear after the next DHCP renewal.

Implications

Automating the renaming process minimizes human error and streamlines network management. However, it’s crucial to maintain a naming convention that enhances network security and clarity.

Recommendations

  • Always back up system settings before running such scripts.
  • Use clear and consistent naming conventions.
  • Test the script in a controlled environment before widespread deployment.

Final thoughts 

In the context of tools like NinjaOne, this script exemplifies the kind of efficient, automated solution that is essential for modern IT management. NinjaOne’s capabilities can complement such scripts, offering a holistic approach to device and network management. Integrating such automation within broader IT management frameworks is key to maintaining robust, secure, and efficient IT environments.

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