修改Linux主机名(hostname)

菜鸟上路CCLinux 2014-05-09

1. 暂时更改hostname

hostname your-hostname

 以下将主机名修改为XD-ORACLE

2. 修改/etc/sysconfig/network配置文件,重启后永久生效

[root@localhost ~]# echo $HOSTNAME
localhost.localdomain

[root@localhost ~]# cp /etc/sysconfig/network /etc/sysconfig/network.bak.modifyHostname
[root@localhost ~]# vi /etc/sysconfig/network

NETWORKING=yes
HOSTNAME=localhost.localdomain

#修改如下
HOSTNAME=XD-ORACLE
[root@localhost ~]# echo $HOSTNAME
XD-ORACLE

3. 修改/etc/hosts本机的域名解析文件

[root@localhost ~]# cp /etc/hosts /etc/hosts.bak.modifyHostname
[root@localhost ~]# vi /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

#修改如下
127.0.0.1   localhost localhost.localdomain XD-ORACLE
::1         localhost localhost.localdomain XJ-ORACLE

4. 相关内容

  1. Linux主机名仅依赖/etc/sysconfig/network配置文件。
  2. /etc/hosts为本机的域名解析文件(类似于现在的DNS,只不过以前的域名不多都可以放进一个文件),修改主机名的时候建议同步修改。
  3. 再shell中直接敲hostname,可能会发现变量名未改变。这是因为该变量来源于 /proc/sys/kernel/hostname(但是用户不需要手动设置)。该文件会随着系统启动时会读取/etc/sysconfig/network并赋值到该hostname变量上。所有下次启动是hostname会自动刷新。

  4. man hostname可以发现又如下描述:

    The host name is usually set once at system startup in /etc/rc.d/rc.inet1 or /etc/init.d/boot (normally by reading the contents of a file which contains the host name, e.g. /etc/hostname).

  5. 本机系统是CentOS6.5 并为发现上述启动配置文件,但是我在另一个系统启动文件里面找到了一些描述:

[root@XD-ORACLE ~]# vi /etc/rc.d/rc.sysinit
#!/bin/bash
#
# /etc/rc.d/rc.sysinit - run once at boot time
#
# Taken in part from Miquel van Smoorenburg's bcheckrc.
#

HOSTNAME=$(/bin/hostname)

set -m

if [ -f /etc/sysconfig/network ]; then
    . /etc/sysconfig/network
fi
if [ -z "$HOSTNAME" -o "$HOSTNAME" = "(none)" ]; then
    HOSTNAME=localhost
fi


#####省略#####


# Use the network address to set the hostname of the client.  This
        # must be done even if we have local storage.
        ipaddr=
        if [ "$HOSTNAME" = "localhost" -o "$HOSTNAME" = "localhost.localdomain" ]; then
                ipaddr=$(ip addr show to 0.0.0.0/0 scope global | awk '/[[:space:]]inet / { print gensub("/.*","","g",$2) }')
                for ip in $ipaddr ; do
                        HOSTNAME=
                        eval $(ipcalc -h $ip 2>/dev/null)
                        [ -n "$HOSTNAME" ] && { hostname ${HOSTNAME} ; break; }
                done
        fi

相关推荐

iamplane / 0评论 2015-02-02