
本文主要介绍在RHEL/CentOS/6/7/8中如何修改主机的hostname。
1、CentOS6/RHEL6
对于6系的红帽Linux,修改hostname较为麻烦,如果只是需要临时修改hostname,只需要使用hostname命令即可:
hostname your-new-temp-hostname
如果需要永久修改hostname,则需要修改两个地方:
首先是/etc/hosts
文件中,需要添加IP
和hostname
的映射关系,如:
127.0.0.1 your-new-perm-hostname
然后在/etc/sysconfig/network
文件中修改对应的HOSTNAME=
参数为新的hostname
HOSTNAME=your-new-perm-hostname
注意两处地方需要同时修改,否则会报错,最后需要重启系统才会生效。
2、CentOS7、8/RHEL7、8
对于7系及之后的红帽Linux,只需要直接修改/etc/hostname
文件然后重启就可以完成永久修改
如果不想重启,可以使用新的hostnamectl
工具来进行永久修改
hostnamectl set-hostname your-new-perm-hostname
3、使用脚本自动执行
#!/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直接执行就可以了。
网友评论