我在我们的嵌入式设备中使用 Ubuntu 18.04。我遵循https://netplan.io/faq通过创建“/etc/networkd-dispatcher/routable.d/50-ifup-hooks”:
#!/bin/sh
echo "Interface up"
# Do something
exit 0
当网线插入路由器时,脚本会被调用。问题是,这个脚本在网线连接后每 5 秒被调用一次。我希望网线插入路由器后只执行“执行某事”,而不是在网线连接后每 5 秒执行“执行某事”。有没有办法确保脚本仅在网线插入路由器后被调用,而在网线已连接到路由器时不执行?
谢谢!
编辑:这是 /etc/networkd-dispatcher 文件夹中的 ll 命令:
root@machine:/etc/networkd-dispatcher# ll
total 28
drwxr-xr-x 7 root root 4096 Sep 20 16:04 ./
drwxr-xr-x 77 root root 4096 Sep 16 18:03 ../
drwxr-xr-x 2 root root 4096 Sep 20 16:05 carrier.d/
drwxr-xr-x 2 root root 4096 Oct 15 2018 dormant.d/
drwxr-xr-x 2 root root 4096 Oct 15 2018 no-carrier.d/
drwxr-xr-x 2 root root 4096 Sep 20 07:12 off.d/
drwxr-xr-x 2 root root 4096 Sep 20 16:04 routable.d/
以下是 carrier.d 文件夹的 ll 命令:
root@machine:/etc/networkd-dispatcher# ll carrier.d/
total 12
drwxr-xr-x 2 root root 4096 Sep 20 16:05 ./
drwxr-xr-x 7 root root 4096 Sep 20 16:04 ../
-rwxr-xr-x 1 root root 209 Sep 20 16:05 50-ifup-hooks*
答案1
routable.d
也许那个小脚本可以帮到你。如果你取消注释,它甚至可以按预期由 netplan (systemd) 从文件夹中调用#NETDEV=${IFACE}
。当然,它不是最终版本,需要做一些工作,但你可以自由地使用它作为基础。
#!/bin/bash
NETDEV=enp0s3
#NETDEV=${IFACE}
TMP_FILE=/tmp/link_state-${NETDEV}
OLD_STATE=
HAS_CARRIER="CARRIER"
HAS_NO_CARRIER="NO_CARRIER"
if [ -e "${TMP_FILE}" ]; then
OLD_STATE=$(cat "${TMP_FILE}")
fi
echo "old_state: ${OLD_STATE}"
RESULT=$(ip link show dev "${NETDEV}" | grep '<NO_CARRIER')
RETVAL=$?
if [ ${RETVAL} -eq 1 ]; then
echo "has a carrier"
if [ "${OLD_STATE}" = "${HAS_CARRIER}" ]; then
echo "no state change"
else
echo -n "${HAS_CARRIER}" > "${TMP_FILE}"
fi
else
echo "${NETDEV} state is currently ${HAS_NO_CARRIER}"
if [ "${OLD_STATE}" = "${HAS_NO_CARRIER}" ]; then
echo "no state change"
else
echo -n "${HAS_NO_CARRIER}" > "${TMP_FILE}"
fi
fi