RHEL/CentOS修改hostname

1、CentOS6/RHEL6

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

hostname your-new-temp-hostname

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

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

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直接执行就可以了。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值