Systemd 在运行服务之前等待网络接口启动

sph*_*how 9 linux startup networking systemd services

我有几个关于 systemd 的问题。在网络接口启动后,我始终无法让我的脚本运行。我已经尝试了 Requires 和 After ,如下所示,但与等待网络启动不一致。我是否使用了正确的服务并正确实施了它?为了现在绕过这个,我正在运行一个非常低效和hackish的ping检查循环。任何建议都会很棒。谢谢!

[Unit]
Description=PBU installer
Requires=network-online.service
After=network-online.service

[Service]
Type=oneshot
ExecStart=/home/pbu/current/scripts/pbu-unpack.sh
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
Run Code Online (Sandbox Code Playgroud)

小智 20

我通过查看以下输出解决了这个问题:

systemctl list-units --no-pager
Run Code Online (Sandbox Code Playgroud)

这向我展示了许多我没想到的单元,就像所有的网络设备一样!

sys-devices-virtual-net-lan0.device loaded active plugged   /sys/devices/virtual/net/lan
Run Code Online (Sandbox Code Playgroud)

所以我加了

BindsTo=sys-devices-virtual-net-lan0.device
After=sys-devices-virtual-net-lan0.device
Run Code Online (Sandbox Code Playgroud)

到我的单元服务文件,然后直到 lan0 可用我的服务才启动。


小智 -1

我不太了解 systemd,但如果您使用 NetworkManager,则可以nm-online在脚本顶部使用 来等待网络启动。

if nm-online; then 
    echo "Online"
    # do my stuff
else
    echo "Network error"
fi
Run Code Online (Sandbox Code Playgroud)

默认情况下,它将等待 30 秒以使网络连接变为活动状态,如果是,则返回 0 (true),否则返回 false。

我认为这至少比 ping 好。