我想在 NetworkManager 连接到某个 WiFi 时启动某个应用程序。但是从DBus中,除了libNotify的通知之外,我找不到来自NetworkManager的此类信号。有更直接的方法吗?
NetworkManager 包括一个nmcli
程序,该程序具有一个monitor
命令。当我断开连接然后连接到 Wi-Fi 接入点时,它的输出如下所示:
$ nmcli monitor
There's no primary connection
wlp4s0: unavailable
Networkmanager is now in the 'disconnected' state
wlp4s0: disconnected
wlp4s0: using connection 'CyberShadowPC'
wlp4s0: connecting (prepare)
Networkmanager is now in the 'connecting' state
wlp4s0: connecting (configuring)
wlp4s0: connecting (need authentication)
wlp4s0: connecting (prepare)
wlp4s0: connecting (configuring)
wlp4s0: connecting (getting IP configuration)
wlp4s0: connecting (checking IP connectivity)
wlp4s0: connecting (starting secondary connections)
wlp4s0: connected
Networkmanager is now in the 'connected' state
'CyberShadowPC' is now the primary connection
Run Code Online (Sandbox Code Playgroud)
看起来应该很容易解析其输出并根据需要运行适当的操作。下面是一个 bash 脚本,当 NetworkManager 连接成为活动的主连接时,该脚本运行一个命令:
#!/bin/bash
set -euo pipefail
connection_name=CyberShadowPC
command=(notify-send "Connected to $connection_name!")
LC_ALL=C nmcli monitor | \
while read -r line
do
if [[ "$line" == "'$connection_name' is now the primary connection" ]]
then
"${command[@]}"
fi
done
Run Code Online (Sandbox Code Playgroud)
Ser*_*nyy -2
虽然当然可以使用dbus
,但就我个人而言,我会使用简单的 bash while 循环 + awk
while [ "$(iwconfig 2> /dev/null | awk '/Access Point/ && /XX:YY:ZZ:11:22:33/ {print "true" }')" != "true" ]; do : ; sleep 0.25 ;done ; echo DONE
Run Code Online (Sandbox Code Playgroud)
那里发生了什么?当循环继续运行时,测试iwconfig
用 过滤掉的输出awk
。只要找不到awk
您想要连接的访问的 MAC 地址,循环就会继续运行。一旦awk
发现您已与该特定 AP 关联,测试条件[ "String1" != "String2" ]
就会变为 false,循环中断,然后继续执行命令echo DONE
。当然,echo DONE
是可以替换成你要运行的程序的。
该命令可以手动运行或放入脚本中,并将脚本添加到启动应用程序列表中。
简单,直接,并且可以完成工作。就像我在开始时所说的那样,可以使用 dbus ,但并不那么简单。