Comprehensive Scripting Guide: Changing the Hostname on a Linux Machine

Key takeaways

  • Automates hostname changes: The script streamlines the process of changing hostnames on Linux systems, enhancing efficiency.
  • Supports multiple functions: Offers options to update hostname, host file, pretty name, and restart the system.
  • Validation and error checking: Incorporates checks for existing commands and validates changes to prevent misconfigurations.
  • User-friendly argument parsing: Simplifies usage with clear arguments for different functionalities.
  • Reduces human error: Automation minimizes the risk of manual mistakes in the hostname changing process.
  • Enhances IT management: A valuable tool for IT professionals and MSPs in managing multiple Linux devices.
  • Script vs Traditional methods: Offers a more efficient approach compared to manual editing of system files.
  • Safety and security: Recommends backups and controlled environment testing to ensure network stability.
  • Integration with management tools: Highlights the benefit of integrating such scripts into platforms like NinjaOne for streamlined operations.
  • Essential for network management: Emphasizes the script’s role in maintaining uniformity and security in network management.

Managing a network of Linux machines involves various tasks, one of which is changing the hostname of a device. This operation, while seemingly straightforward, plays a crucial role in network management and device identification.

Background

The script in question is designed to change the hostname of a Linux device. It’s particularly relevant for IT professionals and Managed Service Providers (MSPs) who manage multiple Linux devices. Such a script ensures uniformity, eases management, and contributes to better security practices.

The script:

#!/bin/bash

# Description: Change the hostname for a linux device (require's hostnamectl/systemd). Host file update expects the hostname to not be fully qualified.
#
# 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 (case sensitive) valid parameters for this script.
# Only the new computer name / pretty name is required!
# Preset Parameter: "ReplaceWithNewComputerName"
# Preset Parameter: "ReplaceWithNewComputerName" --update-hostfile
#   --update-hostfile: Will replace the non-fqdn in /etc/hosts with the name given in the script (will not un-fullyqualify it)
# Preset Parameter: "ReplaceWithNewPrettyName" --prettyname-only
#   --prettyname-only: Set's the 'Pretty' name used by some applications.
# Preset Parameter: "ReplaceWithNewComputerName" --restart
#   --restart: Restart's the machine after updating the hostname. This is required for the new name to take immediate effect.

print_help() {
  printf '\n### Below are all the (case sensitive) valid parameters for this script. ###\n'
  printf '### Only the new computer name / pretty name is required! ###\n'
  printf 'Preset Parameter: "ReplaceWithNewComputerName" \n'
  printf 'Preset Parameter: "ReplaceWithNewComputerName" --update-hostfile \n'
  printf '\t%s\n' "--update-hostfile: Will replace the non-fqdn in /etc/hosts with the name given in the script (will not un-fullyqualify it)"
  printf 'Preset Parameter: "ReplaceWithNewPrettyName" --prettyname-only \n'
  printf '\t%s\n' "--prettyname-only: Set's the 'Pretty' name used by some applications."
  printf 'Preset Parameter: "ReplaceWithNewComputerName" --restart \n'
  printf '\t%s\n' "--restart: Restart's the machine after updating the hostname. This is required for the new name to take immediate effect."
}

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

# Commands required for this script
required_cmds="hostnamectl sed sleep echo"
for i in $required_cmds; do
  check=$(type -P "$i" 2>/dev/null)
  if [[ -z $check ]]; then
    _PRINT_HELP=yes die "FATAL ERROR: The command $i was not found and is required!" 1
  fi
done

# THE DEFAULTS INITIALIZATION - OPTIONALS
_arg_prettyname_only="off"
_arg_update_hostfile="off"
_arg_restart="off"
typical="on"

# Grabbing the parameters and parsing through them.
parse_commandline() {
  while test $# -gt 0; do
    _key="$1"
    case "$_key" in
    --prettyname-only)
      typical="off"
      _arg_prettyname_only="on"
      ;;
    --update-hostfile)
      _arg_update_hostfile="on"
      ;;
    --restart)
      _arg_restart="on"
      ;;
    --*)
      _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
}

# Initializes parameter processing
parse_commandline "$@"

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

if [[ -n $forceRestart && $forceRestart == "true" ]]; then
  _arg_restart="on"
fi

if [[ -n $action ]]; then
  if [[ $action == "Set Pretty Name" ]]; then
    _arg_prettyname_only="on"
    typical="off"
  fi

  if [[ $action == "Set Hostname and Update Host File" ]]; then
    _arg_update_hostfile="on"
  fi
fi

# Old hostname to use when updating the hosts file or checking success
old_name=$(hostname)

# Error out on invalid combo
if [[ $typical == "off" && $_arg_update_hostfile == "on" ]]; then
  _PRINT_HELP=yes die 'FATAL ERROR: --update-hostfile and --prettyname-only cannot be used together.' 1
fi

# If the new computer name isn't given 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 the typical use case is given proceed with changing the hostname
if [[ $typical == "on" ]]; then

  pattern='^[a-zA-Z0-9]([a-zA-Z0-9-]{0,253}[a-zA-Z0-9])?$'
  if [[ $_arg_name =~ [^a-zA-Z0-9-] ]] || [[ ! $_arg_name =~ $pattern ]]; then
    _PRINT_HELP=yes die 'FATAL ERROR: Hostname has invalid characters or spaces. Hostname can only contain A-Z characters, Digits or Hyphens.' 1
  fi

  # Converts the variables to lowercase prior to comparing them
  if [[ "${old_name,,}" == "${_arg_name,,}" ]]; then
    _PRINT_HELP=yes die "FATAL ERROR: The name $old_name is already set. Please enter a new name in the 'Preset Parameter' box in Ninja! For Example 'MyNewName'." 1
  fi

  # Sets the hostname
  hostnamectl set-hostname "$_arg_name"

  # Sleep for a few seconds prior to checking that the change worked
  sleep 7

  current_hostname=$(hostnamectl --static)

  # Checking if the hostname got set correctly
  if ! [[ "${current_hostname,,}" == "${_arg_name,,}" ]]; then
    _PRINT_HELP=no die "FATAL ERROR: Failed to set the hostname from $current_hostname to $_arg_name using hostnamectl is this a systemd system?" 1
  else
    echo "Successfully updated the hostname to '$current_hostname'!"
    printf "\nWARNING: The displayname in Ninja will need to be manually updated however the 'Device Name' section will update itself.\n\n"
  fi

  # If requested to update the hosts file update it
  if [[ $_arg_update_hostfile == "on" ]]; then
    echo "Replacing $old_name in /etc/hosts with $_arg_name (if $old_name is in /etc/hosts at all)"
    sed -i "s/$old_name/$_arg_name/" /etc/hosts
  fi
fi

# If requested to update the pretty name update it
if [[ $_arg_prettyname_only == "on" ]]; then
  current_hostname=$(hostnamectl --pretty)

  if [[ "${current_hostname,,}" == "${_arg_name,,}" ]]; then
    _PRINT_HELP=no die "FATAL ERROR: The pretty name $current_hostname is already set. Please enter a new name in the 'Preset Parameter' box in Ninja! For Example 'MyNewName'." 1
  fi

  hostnamectl set-hostname --pretty "$_arg_name"

  sleep 7

  current_hostname=$(hostnamectl --pretty)
  if ! [[ "${current_hostname,,}" == "${_arg_name,,}" ]]; then
    _PRINT_HELP=no die "FATAL ERROR: Failed to set the pretty name from $current_hostname to $_arg_name using hostnamectl is this a systemd system?" 1
  else
    echo "Successfully updated the pretty name to '$current_hostname'!"
  fi
fi

if [[ $_arg_restart == "on"  ]]; then
  echo "A restart was requested, restarting..."
  shutdown -r
else
  echo "Please restart this computer at your earliest convenience."
fi

 

Access 300+ scripts in the NinjaOne Dojo

Get Access

Detailed breakdown

The script works in the following manner:

  • Initial checks and parameters: It starts by checking the presence of necessary commands like hostnamectl, sed, sleep, and echo. If any are missing, the script outputs an error.
  • Argument parsing: The script accepts various arguments to set the new hostname, update the host file, set the pretty name, or restart the machine. Each argument triggers specific actions within the script.
  • Hostname setting and validation: If the typical scenario is chosen, the script sets the new hostname using hostnamectl and verifies the change.
  • Hosts file update: If requested, the script updates the /etc/hosts file with the new hostname.
  • Pretty name update: For updating the ‘pretty’ name, the script again uses hostnamectl and validates the change.
  • Restart option: Finally, the script offers an option to restart the machine to apply changes immediately.

Potential use cases

Consider an IT administrator in a large organization tasked with renaming several Linux-based servers following a rebranding initiative. Using this script, the administrator can automate the process, ensuring consistency and saving significant time.

Comparisons

Traditionally, changing a hostname involves manually editing files like /etc/hostname and /etc/hosts, followed by a system restart. This script automates these steps, reducing the potential for human error and streamlining the process.

FAQs

  • Is the script compatible with all Linux distributions?
    • It’s designed for systems using hostnamectl, commonly found in modern distributions like Ubuntu, Fedora, and CentOS.
  • What if I only need to change the ‘pretty’ name?
    • Use the –prettyname-only argument. It skips other actions and only updates the pretty name.
  • Is a system restart always necessary?
    • Not always, but a restart ensures the changes are fully applied.

Implications

While the script facilitates hostname changes, incorrect usage can lead to network misconfigurations. It’s crucial to have a proper backup and validation mechanism to avoid disrupting network services.

Recommendations

  • Test the script in a controlled environment first.
  • Ensure you have appropriate permissions before executing the script.
  • Backup essential system files like /etc/hosts before making changes.

Final thoughts

In the realm of device management, tools like NinjaOne provide a comprehensive platform for managing such operations efficiently. Integrating scripts within such systems can further streamline IT management processes, making tasks like changing hostnames a breeze while ensuring consistency and reducing human error.

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

×

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