RHEL/CentOS修改hostname

本文最后更新于:June 16, 2020 pm

本文主要介绍在RHEL/CentOS/6/7/8中如何修改主机的hostname。

1、CentOS6/RHEL6

对于6系的红帽Linux,修改hostname较为麻烦,如果只是需要临时修改hostname,只需要使用hostname命令即可:

1
hostname your-new-temp-hostname

如果需要永久修改hostname,则需要修改两个地方:

首先是/etc/hosts文件中,需要添加IPhostname的映射关系,如:

1
127.0.0.1	your-new-perm-hostname

然后在/etc/sysconfig/network文件中修改对应的HOSTNAME=参数为新的hostname

1
HOSTNAME=your-new-perm-hostname

注意两处地方需要同时修改,否则会报错,最后需要重启系统才会生效。

2、CentOS7、8/RHEL7、8

对于7系及之后的红帽Linux,只需要直接修改/etc/hostname文件然后重启就可以完成永久修改

如果不想重启,可以使用新的hostnamectl工具来进行永久修改

1
hostnamectl set-hostname your-new-perm-hostname

3、使用脚本自动执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/bin/bash
# Determine whether executor is root or not
if [ $(whoami) != "root" ]; then
echo "please exec this shell script with sudo or in root mode"
exit 1
fi

# Determine if there is a new hostname
if [ -z "$1" ]; then
echo "please input the new hostname"
exit 1
fi

# get the release version
version=$(cat /etc/redhat-release | awk -F 'release' '{print $2}' | cut -c -2)

if [ $version -ne 6 ] && [ $version -ne 7 ] && [ $version -ne 8 ]; then
echo "This script do not suit your system, Bye!"
exit 1
fi

echo "your hostname will be change to $1"

if [ $version == 6 ]; then
# get hostname from /etc/sysconfig/network
hostnameCurrent=$(cat /etc/sysconfig/network | grep HOSTNAME | awk -F '=' '{ print $NF }')
# echo "your hostname now is $hostnameCurrent"
# modify the tmp hostname
hostname $1
# Determine if there is a field about $hostnameCurrent in /etc/hosts
# if yes, use awk to replace it
# if no, echo a new line aboout new hostname
cat /etc/hosts | grep $hostnameCurrent
if [ $? -ne 0 ]; then
echo "127.0.0.1 $1" >>/etc/hosts
else
sed -i "s/$hostnameCurrent/$1/g" /etc/hosts
fi
# modify the hostname in /etc/sysconfig/network
sed -i "s/$hostnameCurrent/$1/g" /etc/sysconfig/network
else
if [ $version == 7 ] || [ $version == 8 ]; then
hostnamectl set-hostname $1
fi
fi

echo "Hostname modification is done !"
echo "A restart might be better for apply the change"

将上述的代码保存为脚本再加上需要修改的hostname直接执行就可以了。