我提供了一个侦听dbus信号的脚本,它使您能够比轮询当前网络配置的更改更快地做出反应。它在希望执行脚本/ etc /的系统上不起作用(例如在我的14.04系统上)。
我的输入/输出hooks.d不起作用
NetworkManager会使用-sf /usr/lib/NetworkManager/nm-dhcp-client.action
似乎覆盖正常的进入/退出钩子行为的标志启动dhclient 。dhclient的默认行为是调用中的脚本/etc/dhcp/dhclient-{enter,exit}-hooks.d
。这些在我的系统上根本没有被调用。
我的NetworkManager dispatcher.d脚本也不起作用
但是,NM确实会调用中的另一组脚本/etc/NetworkManager/dispatcher.d
来通知各种事件。NetworkManager(8)手册页定义dhcp4-change
和dhcp6-change
操作似乎完全符合您的要求。尽管什么手册页说,我的系统上至少,只有up
和down
行动被调用。我无法让那些脚本在其他任何东西上触发。因此,这也不是监视IP更改的好方法。
因此,直接监听NM发出的dbus信号
nm-dhcp-client.action
(source)从命令行将dhclient设置的所有环境变量简单地转换为dbus信号。这些环境变量在man dhclient-script
(8)中定义。特别令人感兴趣的是$new_ip_address
。正如@Bernhard所建议的,您可以做的是监视信号并根据其内容采取相应的措施。
这是一个程序,它将侦听该二进制文件发出的所有事件数据:
#!/bin/bash -e
#
# This script listens for the org.freedesktop.nm_dhcp_client signal.
# The signal is emitted every time dhclient-script would execute.
# It has the same contents as the environment passed to
# dhclient-script (8). Refer to manpage for variables of interest.
#
# "org.freedesktop.nm_dhcp_client" is an undocumented signal name,
# as far as I could tell. it is emitted by nm-dhcp-client.action,
# which is from the NetworkManager package source code.
#
# detail: todo cleanup subprocess on exit. if the parent exits,
# the subprocess will linger until it tries to print
# at which point it will get SIGPIPE and clean itself.
# trap on bash's EXIT signal to do proper cleanup.
mkfifo /tmp/monitor-nm-change
(
dbus-monitor --system "type='signal',interface='org.freedesktop.nm_dhcp_client'"
) > /tmp/monitor-nm-change &
exec </tmp/monitor-nm-change
rm /tmp/monitor-nm-change
while read EVENT; do
#change this condition to the event you're interested in
if echo "$EVENT" | grep -q BOUND6; then
# do something interesting
echo "current ipv6 addresses:"
ip addr show | grep inet6
fi
done
dbus-monitor的输出不是直接在脚本中解析的。也许更容易触发某个关键字的存在,例如new_ip_address
,然后从那里使用不同的工具来获取已更改的信息(例如ip或ifconfig)。
# example output data from dbus-monitor for that signal
...
dict entry(
string "new_routers"
variant array of bytes "192.168.2.11"
)
dict entry(
string "new_subnet_mask"
variant array of bytes "255.255.255.0"
)
dict entry(
string "new_network_number"
variant array of bytes "192.168.2.0"
)
dict entry(
string "new_ip_address"
variant array of bytes "192.168.2.4"
)
dict entry(
string "pid"
variant array of bytes "12114"
)
dict entry(
string "reason"
variant array of bytes "REBOOT"
)
dict entry(
string "interface"
variant array of bytes "eth0"
)
...
试一试!
dhclient-enter-hooks.d
脚本实现...但是我从未尝试过!现有的/etc/dhcp/dhclient-enter-hooks.d/resolvconf
脚本可能会对语法和寻找什么信号("$reason" == "BOUND"
可能是?)有所帮助