「Linux」- 修改主机名 @20210127

内容简介

本文主要介绍如何修改主机名。假如pc为原主机名,而我们现在要将laptop作为主机名。

# CentOS 6.10

#!/bin/sh

# 临时修改,重启后会丢失
hostname laptop

# 持久配置
sed 's/HOSTNAME=.+/HOSTNAME=laptop/g' -i /etc/sysconfig/network

# 修改/etc/hosts文件
sed 's/ pc / laptop /g'

# 如果你的命令行提示符还显示以前的主机名,重新登录即可。

# System V

#!/bin/sh

### #1 执行hostname命令
hostname laptop

### #2 修改/etc/hostname文件,将该文件中的pc修改为laptop。
sed -i 's/pc/laptop/g' '/etc/hostname'

### #3 修改/etc/hosts文件,将改文件中的127.0.0.1 pc修改为127.0.0.1 laptop即可。
# 这是一个附加步骤,某些程序需要。
sed -i 's/ pc / laptop /g' /etc/hosts

在其他的Linux发行版中也应该是有效的,毕竟发行版太多了,使用和其机制上也有不同的地方,不敢保证。

# systemd

安装了systemd的Debian版本可以使用hostnamectl命令来更新主机名。该命令依赖于dbus,所以要先确保dbus可以正常工作:

 

# hostnamectl set-hostname laptop

 

该命令会自动修改主机名,并修改/etc/hostname文件,但是该命令不会修改/etc/hosts文件,这可能需要手动完成。

注意事项

有的教程中说要执行/etc/init.d/hostname.sh start命令。emmmm....,一言难尽,不同的发行版里的系统初始进程不同,有用systemd进行管理的,有用SysV风格(init)进行管理的。操作上也由出入。因此,是否要执行该命令与你的修改方法以及你所使用的系统版本有关。该hostname.sh脚本的start方法执行的操作如下(来自于Kali Linux Rolling源):

#!/bin/bash

do_start () {
        [ -f /etc/hostname ] && HOSTNAME="$(cat /etc/hostname)"

        # Keep current name if /etc/hostname is missing.
        [ -z "$HOSTNAME" ] && HOSTNAME="$(hostname)"

        # And set it to 'localhost' if no setting was found
        [ -z "$HOSTNAME" ] && HOSTNAME=localhost

        [ "$VERBOSE" != no ] && log_action_begin_msg "Setting hostname to '$HOSTNAME'"
        hostname "$HOSTNAME"
        ES=$?
        [ "$VERBOSE" != no ] && log_action_end_msg $ES
        exit $ES
}

所以,从上面的脚本看,如果如果你要修改主机名,只需要两步操作:

 

  • 修改/etc/hostname文件,将该文件中的pc修改为laptop
  • 执行/etc/init.d/hostname.sh start命令;

 

而且该脚本也只应该在SysV风格的系统里使用。在Debian 8/9中,使用的是systemd进行系统管理,也不需要执行该命令,也不应该。

常见错误列表

#1 Failed to create bus connection: No such file or directory

执行hostnamectl set-hostname laptop命令时,可能会产生如下错误:

 

Failed to create bus connection: No such file or directory

 

系统:Kali GNU/Linux Rolling
原因:没找到,,,emmmmm...,hostnamectl命令依赖于dbus,dbus需要需要正常运行,这里的正常运行指的是与hostnamectl运行有关的环节正常运行。

参考文献

WikiNotes/修改主机名
How To Change Your Hostname on Debian
Debian Linux: Change Hostname / Computer Name Permanently
How to Change Your Hostname in CentOS 6.7


posted @ 2021-01-27 10:35  研究林纳斯写的  阅读(634)  评论(0编辑  收藏  举报