在 Linux 中永久修改 hostname,不同发行版方式略有不同,下面按常见情况说明。
适用于:CentOS 7/8、RHEL 7+、Ubuntu 16.04+、Debian 8+
hostnamectl set-hostname 新主机名
例如:
hostnamectl set-hostname server01
✅ 会同时修改:
/etc/hostnamehostname
hostnamectl
/etc/hostnamevi /etc/hostname
内容改为:
server01
/etc/hosts(非常重要)vi /etc/hosts
确保有类似:
127.0.0.1 localhost
127.0.1.1 server01
或
192.168.1.10 server01
⚠️ 不改 /etc/hosts 可能导致:
hostname 新主机名
❌ 不推荐用于生产环境
vi /etc/sysconfig/network
修改:
HOSTNAME=server01
然后:
hostname server01
reboot
或仅重启相关服务(如 ssh)
✅ hostname 建议:
- 和 .❌ 避免:
如果你告诉我 具体发行版和版本号(如 Ubuntu 22.04 / CentOS 7),我可以给你最精确的命令。