我使用了 /etc/network/interfaces 中的 pre-up。奇怪的是,我有两个 Ubuntu 服务器,一个是 PC,另一个是 VPS。此方法在我的 PC 上有效,但在 VPS 上无效。
这是我的电脑上的 /etc/network/interfaces
# ifupdown has been replaced by netplan(5) on this system. See
# /etc/netplan for current configuration.
# To re-enable ifupdown on this system, you can run:
# sudo apt install ifupdown
auto dsl-provider
iface dsl-provider inet ppp
pre-up /bin/ip link set eno1 up # line maintained by pppoeconf
provider dsl-provider
#auto eno1
#iface eno1 inet manual
pre-up iptables-restore < /etc/iptables.rules
这是我的 VPS 上的 /etc/network/interfaces
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).
# The loopback network interface
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet static
pre-up iptables-restore < /etc/iptables.rules
source /etc/network/interfaces.d/*
答案1
Netplan 不支持钩子脚本:
https://netplan.io/faq#use-pre-up-post-up-etc-hook-scripts
解决方法是使用 networkd-dispatcher。上面的常见问题解答提供了有关如何操作的示例。
以下是使用 networkd-dispatcher 通过安装在 /etc/networkd-dispatcher/routable.d/50-ifup-hooks 中的脚本运行现有 ifup 钩子的示例:
#!/bin/sh
for d in up post-up; do
hookdir=/etc/network/if-${d}.d
[ -e $hookdir ] && /bin/run-parts $hookdir
done
exit 0
类似地,这里有一个安装在 /etc/networkd-dispatcher/off.d/50-ifdown-hooks 中的 ifdown 钩子的示例:
#!/bin/sh
for d in down post-down; do
hookdir=/etc/network/if-${d}.d
[ -e $hookdir ] && /bin/run-parts $hookdir
done
exit 0