Epics@GSI Webhome

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:
curl -s https://wiki.gsi.de/foswiki/pub/Epics/TipsLinuxDhclientDynamicHostname/_etc_dhcp_dhclient-exit-hooks.d_hostname -o /etc/dhcp/dhclient-exit-hooks.d/hostname && 
   dos2unix /etc/dhcp/dhclient-exit-hooks.d/hostname && 
   chmod a+r /etc/dhcp/dhclient-exit-hooks.d/hostname

Local testing at the prompt:
dhclient


-- PeterZumbruch - 2018-05-02
-- PeterZumbruch - 2018-11-30

Topic attachments
I Attachment Action Size Date Who Comment
_etc_dhcp_dhclient-exit-hooks.d_hostnamed_hostname _etc_dhcp_dhclient-exit-hooks.d_hostname manage 1.0 K 2018-04-27 - 14:07 PeterZumbruch /etc/dhcp/dhclient-exit-hooks.d/hostname
Topic revision: r9 - 2018-11-30, PeterZumbruch
 
This site is powered by FoswikiCopyright © by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding GSI Wiki? Send feedback
Imprint (in German)
Privacy Policy (in German)