« Angell Hall Cyberstation - Color Printing fix | Main | Quick script to back up a transcript »
May 22, 2008
Set Hostname to Network-Supplied Hostname
Nobody wants their production machines to have hostnames like “Sites’ iMac.” To get around this issue, we created a script called HostNamer to find the hostname and set it. Under Tiger, we got away with calling hostname -s, but under Leopard this would often return the current hostname, not the desired one. So, we created a script to look at the DNS entry for the computer's IP address.
#!/bin/bash
# HostNamer - Gets proper hostname from server and tells OS X to use it.
PATH=/bin:/usr/bin:/usr/sbin:/sbin:/usr/local/bin; export PATH
get_ip(){
IPADDR="`/sbin/ifconfig en0 | awk '{ if ( $1 == "inet" ) print $2 }'`"
IPBEGIN="`echo ${IPADDR} | awk '{ split($1, a, "."); print a[1] }'`"
}
# Get IP address.
get_ip
# Make sure that IP is valid (i.e. starts with "141.") If not, wait and try again.
# Will only try 10 times.
count=0
while [ "${IPBEGIN}" != "141" ]; do
let "count += 1"
echo $count
if [ $count -gt 10 ]; then
logger -is Failed to get correct IP address.
exit 1
fi
sleep 10
get_ip
done
HOSTNAME="`host ${IPADDR} | awk ' { for ( x = 1; x < 20; x++ ) if ( $x == "pointer" ) print $(x+1) }' | awk '{ split($1, a, "."); print a[1] }'`"
scutil --set ComputerName "${HOSTNAME}"
scutil --set LocalHostName "${HOSTNAME}"
scutil --set HostName "${HOSTNAME}"
# Now, rename the disk.
# Get the correct disk name to use
DiskName="`diskutil list | grep -m 1 Apple_HFS | awk '{ print $NF }'`"
diskutil rename $DiskName $HOSTNAME
The portion that checks for a correct IP (for us, 141) is there because on Intel-based Macs, we noticed that the script was called before the network was up—we’re running it via a StartupItem. We also created a link to this script in our Radmind post-apply folder, so the system will be renamed before rebooting. That way, it comes up with its correct name. Finally, we rename the hard disk to the hostname to allow for easy identifiation of in-use computers.
Posted by slauncha at May 22, 2008 09:56 AM