3

I've already seen this link How to make Raspberry shutdown when I unplug the ethernet cable, but this solution does not work on Raspbian stretch since its network interface file/folder structure is changed.

My Raspberry pi is headless and battery powered (assume that it will give backup around 10min), so whenever electricity is gone for long time I want it to shutdown properly. Also note that when electricity goes down my network also goes down, so can't use ssh.

Any suggestion?

3 Answers 3

4

use post-up and post-down hook options in network script /etc/network/interfaces ,

you can create a simple script for shutdown, lets call it sd.sh executing which system will be shut down, so your network interfaces script will look like

# For static IP, consult /etc/dhcpcd.conf and 'man dhcpcd.conf'

# Include files from /etc/network/interfaces.d:
source-directory /etc/network/interfaces.d

allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp
    post-down ~myPath~/sd.sh
1
  • This may be OK - provided you don't mind breaking the standard Raspbian dhcpcd networking.
    – Milliways
    Mar 25, 2018 at 22:53
4

EDIT 2: You can use a dhcpcd exit hook script. The script is called on each dhcpcd event and checks the reason for calling dhcpcd and the related interface.

Create the script /etc/dhcpcd.exit-hook (usually it doesn't exists, otherwise edit it):

if [ "$reason" = NOCARRIER ] && [ "$interface" = eth0 ]
then
  echo "$(date) - eth0 DOWN, will shutdown now" >> /log/eth0_shutdown.log
  poweroff
fi

Note that this script file doesn't need to have a first line like #!/bin/bash and it also doesn't need to be set as executable.

Create the folder /log if it doesn't exists

sudo mkdir /log

Edit 1: If a cron job is too slow, then a while loop may be used instead. Adjust the sleep time as required.

#!/bin/bash

while [ $(cat /sys/class/net/eth0/operstate) == "up" ]
do
  sleep 10
done
echo "LAN is down, will shutdown now"
poweroff

First answer

You can monitor the interface status with a script which is regularly called by a cron job.

if [ $(cat /sys/class/net/eth0/operstate) == "down" ]
then 
   echo "LAN is down, will shutdown now"
   poweroff
fi
1

Got a better solution... I've used the lan connection for internet and configure the wifi as AP using the following link https://github.com/SurferTim/documentation/blob/6bc583965254fa292a470990c40b145f553f6b34/configuration/wireless/access-point.md

Then connect to the AP using mobile (android) with any ssh client and send the shutdown command to shut it down properly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.