You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用systemd无需注销修改主机名,在系统设置主机名前执行脚本

问题原因

systemd PID 1 读取/etc/hostname并打印Set hostname to XYZ日志的动作发生在开机启动极早期,远早于multi-user.target关联服务的执行时机,同时你当前的服务配置存在循环依赖错误(同时声明了After=network-pre.service和Before=network-pre.service),导致服务启动时序不符合预期。

修复方案

1. 调整服务配置

将服务插入到sysinit.target执行序列的前置位置,确保修改/etc/hostname的动作发生在systemd读取该文件之前,修改后的完整配置如下:

[Unit]
Description=Hostname Setting Service
After=read_variables.service
Requires=read_variables.service
# 确保在systemd读取hostname、启动hostnamed之前执行
Before=systemd-sysctl.service systemd-hostnamed.service sysinit.target
DefaultDependencies=false

[Service]
ExecStart=/bin/bash -c "NEW_HOSTNAME=\"name$VARIABLE\"; echo \"$NEW_HOSTNAME\" > /etc/hostname; hostname \"$NEW_HOSTNAME\""
StandardOutput=journal+console
EnvironmentFile=/folder/environment_output.txt
Type=oneshot
RemainAfterExit=yes

[Install]
# 关联到sysinit.target保证启动时机足够早
WantedBy=sysinit.target

2. 生效配置

执行以下命令启用新配置:

systemctl daemon-reload
# 替换为你实际的服务文件名
systemctl enable your-hostname-service.service

生效逻辑

  • 服务现在会在sysinit.target执行早期运行,在systemd PID 1读取/etc/hostname之前就完成文件内容修改,systemd打印日志时读取到的就是新的主机名
  • 额外添加的hostname命令会直接更新内核运行时主机名,即使出现极端时序偏差也能保证主机名正确

内容的提问来源于stack exchange,提问作者EagleOne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 08:06:03