Dhcpdcd, which is used for DHCP client negotiation by default in Raspbian/RpiOS, has a "hooks" directory in /lib/dhcpcd/dhcpcd-hooks
. Beware not to confuse dhcpcd
with dhclient
, which can serve much the same purpose and also entertains hooks (but is not used by default), or dhcpd
(one less letter), which acts as a DHCP server (the cd
in dhcpcd
is for "client daemon").
man dhcpcd-run-hooks
documents this very succinctly. When the script is run by dhcpd
, the environment will contain a bunch of variables with information. There is a list of a dozen or so reasons that this will happen; the specific one will be in $reason
.
Try placing this there:1
reportLog=/some/absolute/path/dhcpcd-report.log
msg() {
echo $@ >> $reportLog
}
date >> $reportLog
msg Invoked for $reason
'printenv' dumps all the environment variables
printenv >> $reportLog
echo >> $reportLog
An example of the output:
Mon Jan 25 17:12:03 EST 2021
Invoked for BOUND
new_subnet_cidr=24
new_ip_address=192.168.0.21
new_network_number=192.168.0.0
pid=427
new_dhcp_message_type=5
if_down=false
ifmtu=1500
new_routers=192.168.0.1
new_subnet_mask=255.255.255.0
interface=wlan0
new_domain_name=hitronhub.home
reason=BOUND
ifcarrier=up
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
ifssid=ISS2
protocol=dhcp
interface_order=lo eth0 wlan0
new_host_name=raspberrypi
if_up=true
new_dhcp_server_identifier=192.168.0.1
new_domain_name_servers=64.71.255.204 64.71.255.198
new_broadcast_address=192.168.0.255
WPAconfig=/etc/wpa_supplicant/wpa_supplicant.conf
ifflags=69699
PWD=/
ifmetric=303
ifwireless=1
new_dhcp_lease_time=604800
A couple of the variables are inherited from the system ($PATH
, $PWD
), the rest are all from dhcpcd
(many/most of them are described in the hooks man page). Of particular relevance to you is of course if_up=true
. You'll have to experiment a bit to decide when you should do what it is you want to do. For example, there's a distinction between an interface going up and an actual connection being established, and some specific combination of $reason
and $interface
may be the key you want to watch for; if you just do it every time a hook is run with if_up=true
you will end up doing it three or four times in rapid succession, etc.
Dhcpcd executes this via sh
(which is why there is no point in a shebang #!/___
), meaning you can't use bashisms like exec &>
to redirect all output (hence the cumbersome msg()
function above) or capture the output of a command in a variable with foo=$(bar)
. However, you can get around that by making the hook script just:
/bin/bash /path/to/some/bashscript.sh
You could do something similar to run a python script or execute anything; those environment variables are inherited.
out.txt
, otherwise it is likely to end up not where you thought it would. – goldilocks Feb 01 '21 at 19:30