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: %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
-- PeterZumbruch - 2020-11-09

I Attachment Action Size Date Who Comment
_etc_dhcp_dhclient-exit-hooks.d_hostnamed_hostname _etc_dhcp_dhclient-exit-hooks.d_hostname manage 979 bytes 2018-04-27 - 16:07 PeterZumbruch /etc/dhcp/dhclient-exit-hooks.d/hostname
Topic revision: r10 - 2020-11-09, PeterZumbruch - This page was cached on 2024-12-19 - 18:56.

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 | Legal notice | Privacy Policy (german)