You are here: Home / Debian GNU/Linux / System / Setup / Change the hostname of a Debian GNU/Linux host

Change the hostname of a Debian GNU/Linux host

by Pierre-Yves Landuré last modified Jun 30, 2013 03:40

This howto ease the change of the hostname of a computer running Debian GNU/Linux. It should be useful to people using Debian virtual machine cloning.

This howto is tested on:

  • Debian 6.0 Squeeze
  • Debian 7.0 Wheezy

Parameters

Provide the new hostname, with the new domain if necessary :

NEW_FQDN="myhost.domain.lan"

Configuration

Detect the new hostname :

NEW_HOSTNAME="$(echo "${NEW_FQDN}" | command cut --delimiter="." --fields=1)"

Detect the current hostname :

CURRENT_FQDN="$(command hostname --fqdn)"
CURRENT_HOSTNAME="$(command hostname)"

Update the configuration files:

declare -a FILES
FILES[0]="/etc/hostname"
FILES[1]="/etc/motd"
FILES[2]="/etc/hosts"
FILES[3]="/etc/mailname"
FILES[4]="/etc/exim4/update-exim4.conf.conf"
for FILE in ${FILES[@]}; do
if [ -e "${FILE}" ]; then
  command sed -i -e "s/${CURRENT_FQDN}/${NEW_FQDN}/" "${FILE}"
command sed -i -e "s/${CURRENT_HOSTNAME}/${NEW_HOSTNAME}/" "${FILE}"
fi
done

Reload the hostname :

command hostname --file "/etc/hostname"

Update the Exim 4 configuration :

command update-exim4.conf

Generate a new key for the SSH server :

command rm "/etc/ssh/ssh_host_rsa_key" "/etc/ssh/ssh_host_rsa_key.pub" \
 "/etc/ssh/ssh_host_dsa_key" "/etc/ssh/ssh_host_dsa_key.pub"
command ssh-keygen -q -t rsa -N "" -C "root@${NEW_HOSTNAME}" -f "/etc/ssh/ssh_host_rsa_key"
command ssh-keygen -q -t dsa -N "" -C "root@${NEW_HOSTNAME}" -f "/etc/ssh/ssh_host_dsa_key"

Restart the SSH server :

/etc/init.d/ssh restart

The new hostname will be active at your next login.