hmx-17の日記

技術ネタとかプライベート

Raspberry Pi の DHCP更新のタイミングでスクリプトを実行させる

やりたいこと

Raspberry Piのeth0についてるIPアドレスが変更されたら、
プログラムを実行させたい

やりかた

簡単に言うと: dhcpcd-hooksを使う
sudo nano /lib/dhcpcd/dhcpcd-hooks/01-renew
とかに

 if [ "$reason" = "BOUND" ]; then
        if [ "$interface" = "eth0" ]; then
                IP=`/sbin/ip -f inet -o addr show eth0|cut -d\  -f 7 | cut -d/ -f 1`
                echo $IP >> /home/pi/bound.txt
                /usr/bin/wget [some-ome-host] -O - > /dev/null
        fi
        exit 0
 fi

 if [ "$reason" = "RENEW" ]; then
        if [ "$interface" = "eth0" ]; then
                IP=`/sbin/ip -f inet -o addr show eth0|cut -d\  -f 7 | cut -d/ -f 1`
                /usr/bin/wget [some-ome-host] -O - > /dev/null
        fi
        exit 0
 fi

と書けばとりあえずOKです。今回はwgetで特定のサイトに通知させたかったのですが、 $IPを引数にした何かのスクリプトでもいいと思います。