ThreadStates

Setting Hostnames After Imaging

One problem with imaging multiple computers from a master image is that they all end up with the same hostname. This is especially bothersome on OS X, because there are two different hostnames: the one returned by hostname, and the one listed in the Sharing preferences pane.

To handle this problem, I wrote the following script, which is OS X specific, and works in Leopard. You may need to adjust the path to networksetup to get it working on other versions.

It sets both hostnames to the same user-defined value based on a network interface's MAC address. Hostnames may not contain spaces. Simply include it (and the mac/hostname file) in your master image and execute it via ssh or ARD after deploying your image.

sethostname

#!/bin/bash

#------------------------------------------------------------------
# Set a computer's hostname.  OS X specific.
#
# Usage: sethostname <interface> </path/to/hostnames/file>
#
# The hostnames file must be a list of mac addresses and hostname
# pairs, one per line, separated by whitespace. Run the script on
# the computer whose hostname you want to change. The hostname 
# cannot contain spaces.
#
# Peter Morris 05.Jan.2008
#
# Made Leopard compatable; changed path to networksetup.
#------------------------------------------------------------------

usage() {
    echo "Usage: # $0 <interface> </path/to/hostnames/file>" >&2
}

#---------------------------------
# Check usage.
#---------------------------------
if [ $(whoami) != 'root' ]; then
    echo "$(basename $0) must be run as root"
    exit 1
fi

if [ $# != 2 ]; then
    usage
    exit 1
fi

if [ -f $2 ]; then
    hostfile=$2
else
    echo "$2 is not a regular file"
    exit 1
fi

#---------------------------------
# Find the hostname and apply it.
#---------------------------------
iface=$1
mac=$(ifconfig $iface | awk '/ether/ {print $2}')
hostname=$(awk "/$mac/ {print \$2}" $hostfile)

if [[ $hostname == "" ]]; then
    echo "Problem getting hostname, check $hostfile" >&2
else
    scutil --set HostName $hostname
    /usr/sbin/networksetup -setcomputername $hostname
fi