R&D/클라우드

ubuntu hostname update based on dhcp

sunshout 2014. 5. 22. 20:42

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"
export
set -x
 
if [ $reason = "BOUND" ]; then
echo new_ip_address=$new_ip_address
echo new_host_name=$new_host_name
echo new_domain_name=$new_domain_name
 
oldhostname=$(hostname -s)
if [ $oldhostname != $new_host_name ]; then
 
# Rename Host
echo $new_host_name > /etc/hostname
hostname -F /etc/hostname
 
# Update /etc/hosts if needed
TMPHOSTS=/etc/hosts.dhcp.new
if ! 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 installer
grep -v '127\.0\.1\.1 ' < /etc/hosts > $TMPHOSTS
# Add the our new ip address and name
echo "$new_ip_address $new_host_name.$new_domain_name $new_host_name" >> $TMPHOSTS
mv $TMPHOSTS /etc/hosts
fi
 
# Recreate SSH2 keys
export DEBIAN_FRONTEND=noninteractive
dpkg-reconfigure openssh-server
fi
fi
echo "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.