Script – Changer le hostname d’un serveur CentOS – RedHat

Dans les outils utiles, mention spéciale pour distribuer aux petits admin qui doivent renommer leur serveur RedHat / CentOS.

Ce petit script vous changera le hostname de votre serveur sous CentOS et RedHat sans redémarrer la machine. Simple. Efficace.

#!/bin/bash

#################################
#    FILE: change_hostname.sh   #
#    VERSION: 0.1               #
#    DATE: 08-04-2015           #
#                               #
#    AUTHOR: Thomas Bourcey     #
#################################

#############################################
#  USAGE :                                  #
#  $ sh change_hostname.sh new_hostname     #
#  or                                       #
#  $ sh change_hostname.sh                  #
#  Please enter new hostname: new_hostname  #
#############################################


if [ $EUID -ne 0 ]; then
        echo "The script must be run as root: # su - -c $0 or # sudo ./$0"
        exit 1
fi

$ command -v lsb_release >/dev/null 2>&1 || { echo >&2 "Package redhat-lsb-core is required. Download it \"yum install -y redhat-lsb-core\".  Aborting."; exit 1; }

if [ `lsb_release -a | grep -i Distributor | awk -F":" '{print $2}' | tr -d '[ \t ]'` != "RedHatEnterpriseServer" ]; then
        echo "Only for RedHat Distribution. Exiting !"
        exit 2
fi

OLD_HOSTNAME="$( hostname )"
NEW_HOSTNAME="$1"

if [ -z "$NEW_HOSTNAME" ]; then
 echo -n "Please enter new hostname: "
 read NEW_HOSTNAME < /dev/tty
fi

if [ -z "$NEW_HOSTNAME" ]; then
 echo "Error: no hostname entered. Exiting."
 exit 1
fi

echo "Changing hostname from $OLD_HOSTNAME to $NEW_HOSTNAME..."

hostname "$NEW_HOSTNAME"

sed -i "s/HOSTNAME=.*/HOSTNAME=$NEW_HOSTNAME/g" /etc/sysconfig/network

if [ -n "$( grep "$OLD_HOSTNAME" /etc/hosts )" ]; then
 sed -i "s/$OLD_HOSTNAME/$NEW_HOSTNAME/g" /etc/hosts
else
 echo -e "$( hostname -I | awk '{ print $1 }' )\t$NEW_HOSTNAME" >> /etc/hosts
fi

echo "Done."