在 Linux 系统中,查询 hostname(主机名) 有多种常用方法,以下按使用频率和场景分类说明:
hostnamehostname
直接输出当前主机名。
uname -nuname -n
-n 表示显示网络节点主机名。
hostnamectl(推荐,systemd 系统)hostnamectl
或只查看主机名:
hostnamectl --static
hostnamectl --transient
hostnamectl --pretty
适用于 CentOS 7+/Ubuntu 16.04+ 等使用 systemd 的系统。
/etc/hostnamecat /etc/hostname
这是系统启动时使用的静态主机名。
/etc/hostscat /etc/hosts
可看到主机名与 IP 的映射关系。
$HOSTNAMEecho $HOSTNAME
注意:该变量在某些 shell 或非登录环境中可能为空。
hostname -f(FQDN)hostname -f
显示完整域名(如 node1.example.com)。
hostname -Ihostname -I
显示主机所有 IP 地址(不是主机名,但常一起用)。
| 场景 | 推荐命令 |
|---|---|
| 快速查看 | hostname |
| systemd 系统 | hostnamectl |
| 看配置文件 | cat /etc/hostname |
| 看完整域名 | hostname -f |
如果你是想 修改 hostname 或 在脚本中获取主机名,也可以告诉我,我可以进一步说明。