在Linux系统中,可以通过以下几种方法检查当前主机名:
hostname
命令hostname
这个命令会直接输出当前系统的主机名。
hostnamectl
命令(systemd系统)hostnamectl
这会显示主机名及相关信息(静态/动态主机名、操作系统等)。
如果只需要主机名:
hostnamectl --static
hostnamectl --transient
hostnamectl --pretty
/etc/hostname
文件cat /etc/hostname
这个文件保存着系统的静态主机名。
uname
命令uname -n
-n
参数会显示网络节点主机名。
echo $HOSTNAME
注意:这个方法获取的是shell会话中的主机名变量,可能在某些情况下与真实主机名不同。
/proc/sys/kernel/hostname
cat /proc/sys/kernel/hostname
这个虚拟文件也包含当前内核使用的主机名。
临时修改:
hostname newname
永久修改(systemd系统):
hostnamectl set-hostname newname
非systemd系统:
# 修改/etc/hostname文件
echo "newname" > /etc/hostname
# 然后运行
hostname -F /etc/hostname
修改后建议同时更新/etc/hosts文件中对应的条目。