CentOS7中关系到hostname设置的文件和方法比较多,整个感觉有点混乱,可能是因为有多个团队在负责不同的文件与方法,没有统一的管理,逻辑有点混乱。下面是我自己通过反复实验整理出来的,供大家参考。
(1) $hostnamectl 命令
$hostnamectl 返回hostname所有信息
Static hostname: localhost.localdomain
Transient hostname: lj1402 //可能不显示,尤其是当Static hostname不是localhost.localdomain的时候,我认为是问题
Icon name: computer-laptop
Chassis: laptop
Machine ID: 80394d0cxxxxxxxx6e42da3a
Boot ID: 281a329ffaxxxxxxxx48e08ad9847
Operating System: CentOS Linux 7 (Core)
CPE OS Name: cpe:/o:centos:centos:7
Kernel: Linux 3.10.0-957.1.3.el7.x86_64
Architecture: x86-64
$hostnamectl --static //显示static hostname
$hostnamectl --transient //显示transient hostname
(2)static hostname设置
$vim /etc/hostname <hostname> //在hostnamectl 可以立即查询得到
或 $hostnamectl --static set-hostname <hostname>//在hostnamectl 可以立即查询得到, 且/etc/hostname也修改了,
注意,如果<hostname> 不是localhost.localdomain, 则该命令同时修改了static hostname和transient hostname,所以$hostnamectl 只返回static hostname信息, $hostname 和 $cat /proc/sys/kernel/hostname返回为该<hostname>, shell重新登陆生效 , 重启后不变。
如果<hostname> 是localhost.localdomain, $hostname 和 $cat /proc/sys/kernel/hostname返回为transient hostname. 但这个transient hostname的取值为系统以前取值的一个,不太有规律,尤其是当从非localhost.localdomain切换到localhost.localdomain时,我觉得有问题
重启后会有什么变化呢?这要看/etc/hosts文件的内容,例如
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.1.109 lj1402
如果 localhost.localdomain对应的是127.0.0.1 , 则重启时系统会在这个表里去找第一个和本地IP地址对应的hostname,如本地地址是192.168.1.108, 则transient hostname变成el.node.cn. 如果/etc/hosts里没有本地IP地址对应的这一项记录,则重启后transient hostname也变成 localhost.localdomain
(3) Transient hostname设置
$hostnamectl --transient set-hostname <hostname>//在hostnamectl 可以立即查询得到,重新登陆后生效,
如果static hostname不是localhost.localdomain,则$hostname 和 $cat /proc/sys/kernel/hostname返回为static hostname,
如果static hostname是localhost.localdomain,则$hostname 和 $cat /proc/sys/kernel/hostname返回为transient hostname,
重启后重置
(4) hostname 和 /proc/sys/kernel/hostname
$hostname <new hostname> //在hostnamectl --transient可以立即查询得到,shell重新登陆后生效,
$echo <new hostname> >/proc/sys/kernel/hostname //在hostnamectl --transient可以立即查询得到,shell 重新登陆后生效
两种方法重启后都会重置