To run a script when the WiFi is connected you can use wpa_cli. In man wpa_cli
you find for option -a
:
-a file
Run in daemon mode executing the action file based on events from wpa_supplicant. The specified file will be executed with the first argument set to interface name and second to "CONNECTED" or "DISCONNECTED" depending on the event. This can be used to execute networking tools required to configure the interface.
Additionally, three environmental variables are available to the file:
WPA_CTRL_DIR, WPA_ID, and WPA_ID_STR. WPA_CTRL_DIR contains the absolute path to the ctrl_interface socket. WPA_ID contains the unique network_id identifier assigned to the active network, and WPA_ID_STR contains the content of the id_str option.
As template file you can use something like this:
#!/bin/sh
# redirect all output into a logfile
exec 1>> /tmp/test.log 2>&1
case "$1" in
wlan0)
case "$2" in
CONNECTED)
# do stuff on connect with wlan0
echo wlan0 connected
;;
DISCONNECTED)
# do stuff on disconnect with wlan0
echo wlan0 disconnected
;;
*)
>&2 echo empty or undefined event for wlan0: "$2"
exit 1
;;
esac
;;
wlan1)
case "$2" in
CONNECTED)
# do stuff on connect with wlan1
echo wlan1 connected
;;
DISCONNECTED)
# do stuff on disconnect with wlan1
echo wlan1 disconnected
;;
*)
>&2 echo empty or undefined event for wlan1: "$2"
exit 1
;;
esac
;;
*)
>&2 echo empty or undefined interface: "$1"
exit 1
;;
esac
Don't forget to make the script executable with chmod +x script.sh
. Then execute it with:
rpi ~$ wpa_cli -i wlan0 -a /home/pi/path/to/script.sh
# Or if necessary as root:
rpi ~$ sudo wpa_cli -i wlan0 -a /path/to/script.sh
If you want to run it as daemon then add option -B
.
ps aux
command shows that the script is running on the background. Help me? – mcv Apr 10 '19 at 04:08/tmp/test.log
. In additionwpa_cli
needs the right interface to manage. I have added option-i wlan0
to the test commands. – Ingo Apr 11 '19 at 16:24