Execute script at network connect/disconnect

How to do things, solutions, recipes, tutorials
Post Reply
Message
Author
Ibidem
Posts: 549
Joined: Wed 26 May 2010, 03:31
Location: State of Jefferson

wpa_cli action scripts

#1 Post by Ibidem »

Have you ever wanted to execute something automatically on network connect/disconnect?
If you use wpa_supplicant to connect, you can. This is most useful for properly timing a DHCP request, but there are other uses...
I gave a summary of this here (my second post, near the end of that page), but there are some possible extensions to the idea.
The basic idea is that if wpa_cli isinvoked with -a <action script>, it will execute the script with certain parameters...

Starting script (assumes a working udhcpc):

Code: Select all

#!/bin/sh
#wpa_cli invokes this on network connection/disconnect
#as $0 $IFACE CONNECTED or DISCONNECTED
case $2 in
CONNECTED)
udhcpc -i $1 -h `hostname`
;;
DISCONNECTED)
;;
*)
;;
esac 
Of course, this has a slight problem: it may result in multiple udhcpc instances managing the same interface. Usually this works fine, but here's how one could avoid it. I threw in some code to allow deconfiguring an interface.

Code: Select all

#!/bin/sh
PIDFILE=/var/run/udhcpc/${1}.pid
get_lease()(
mkdir -p `dirname $PIDFILE`
kill `cat $PIDFILE`
udhcpc -i $1 -h `hostname` -f -p $PIDFILE
rm -f $PIDFILE
)

case $2 in
CONNECTED)
get_lease $1 &
;;
DISCONNECTED)
kill `cat $PIDFILE`
;;
stop)
kill `cat $PIDFILE`
wpa_cli -i $1 -p /var/run/wpa_supplicant terminate
;;
*)
cat <<EOF >&2
Usage: 
wpa_cli -a $0 -B : Use as wpa_cli action script
$0 eth1 CONNECTED : signal network connect/get a DHCP lease
$0 wlan0 DISCONNECTED : signals network disconnect
$0 ra0 stop : Kill wpa_supplicant/ deconfigure interface
EOF
esac 

Post Reply