Tips Linux Dhclient Dynamic Hostname
Introduction
Using
dhclient
exit hooks scripts allows to set e.g. the
hostname
dynamically.
Based on the articles:
and its own origin
dhclient
and its scripting capabilities on enter and exit hooks allows to react on dynamic network environments.
Provided you have root privileges this can be achieved by creating a script file
hostname
created in
/etc/dhcp/dhclient-exit-hooks.d/
(on Debian), which is sourced by
dhclient
after having updated/received its DHCP informations.
#!/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" ] && [ "$interface" != "eth1" ] && [ "$interface" != "wlan0" ]
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=$(a=$(host $new_ip_address) || { false; } && { echo -n $a | cut -d ' ' -f 5 | cut -d "." -f 1; true; }) || unset hostname &&
echo ${hostname?} > /etc/hostname &&
hostname $hostname &&
export HOSTNAME=$hostname &&
echo dhclient-exit-hooks.d/hostname: Dynamic Hostname = $hostname
Applying those code lines:
%FOREACH{"file" in="/etc/dhcp/dhclient-exit-hooks.d/hostname"}%
curl -s https://wiki.gsi.de/pub/Epics/TipsLinuxDhclientDynamicHostname/_etc_dhcp_dhclient-exit-hooks.d_hostname -o $file &&
dos2unix $file &&
chmod a+r $file
%NEXT{"file"}%
Local testing at the prompt:
dhclient
--
PeterZumbruch - 2018-05-02