edit /etc/dhcp/dhclient-exit-hooks.d/hostname
#!/bin/sh# dhclient change hostname script for Ubuntu# /etc/dhcp/dhclient-exit-hooks.d/sethostname# logs in /var/log/upstart/network-interface-eth0.log# for debugging:echo "sethostname BEGIN"exportset -xif [ $reason = "BOUND" ]; thenecho new_ip_address=$new_ip_addressecho new_host_name=$new_host_nameecho new_domain_name=$new_domain_nameoldhostname=$(hostname -s)if [ $oldhostname != $new_host_name ]; then# Rename Hostecho $new_host_name > /etc/hostnamehostname -F /etc/hostname# Update /etc/hosts if neededTMPHOSTS=/etc/hosts.dhcp.newif ! grep "$new_ip_address $new_host_name.$new_domain_name $new_host_name" /etc/hosts; then# Remove the 127.0.1.1 put there by the debian installergrep -v '127\.0\.1\.1 ' < /etc/hosts > $TMPHOSTS# Add the our new ip address and nameecho "$new_ip_address $new_host_name.$new_domain_name $new_host_name" >> $TMPHOSTSmv $TMPHOSTS /etc/hostsfi# Recreate SSH2 keysexport DEBIAN_FRONTEND=noninteractivedpkg-reconfigure openssh-serverfifiecho "sethostname END"
If not working,
#!/bin/sh
# Filename: /etc/dhcp/dhclient-exit-hooks.d/hostname
# Purpose: Used by dhclient-script to set the hostname of the system
# to match the DNS information for the host as provided by
# DHCP.
#
# Do not update hostname for virtual machine IP assignments
if [ "$interface" != "eth0" ]
then
return
fi
if [ "$reason" != BOUND ] && [ "$reason" != RENEW ] \
&& [ "$reason" != REBIND ] && [ "$reason" != REBOOT ]
then
return
fi
echo dhclient-exit-hooks.d/hostname: Dynamic IP address = $new_ip_address
hostname=$(host $new_ip_address | cut -d ' ' -f 5)
echo $hostname > /etc/hostname
hostname $hostname
echo dhclient-exit-hooks.d/hostname: Dynamic Hostname = $hostname
Make sure it is readable...
chmod a+r /etc/dhcp/dhclient-exit-hooks.d/hostname
That's all. On the next dhcp response your hostname will update automatically.