Skip to content

Instantly share code, notes, and snippets.

@frgaudet
Created May 25, 2015 06:48
Show Gist options
  • Save frgaudet/0c8b033983d150c2ebc2 to your computer and use it in GitHub Desktop.
Save frgaudet/0c8b033983d150c2ebc2 to your computer and use it in GitHub Desktop.
Apply hostname from DNS
#!/bin/sh
# Apply hostname from DNS server
# Author : F-Gaudet 2014
# Usage : drop this file into /etc/NetworkManager/dispatcher.d
interface=$1 status=$2
if [ $status = up ]; then
ip=$(ip addr | grep $interface: -A2 | tail -n1 | awk '{print $2}' | cut -f1 -d'/' )
string=$(host $ip) > /dev/null
ret=$?
if [ $ret = 0 ]; then
new_hostname=$(echo $string | cut -d ' ' -f 5 | cut -d '.' -f 1)
if [ -n "$new_hostname" ]; then
current_hostname=$(hostname)
if [ "$new_hostname" != "$current_hostname" ]; then
echo $new_hostname > /etc/hostname
hostname $new_hostname
domain=$(dnsdomainname)
if [ -n "$domain" ]; then
sed -i "s/^127.0.1.1.*/127.0.1.1 $new_hostname $new_hostname.$domain/" /etc/hosts
else
sed -i "s/^127.0.1.1.*/127.0.1.1 $new_hostname/" /etc/hosts
fi
fi
fi
else
echo "Host not found"
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment