Automatically Shutdown a RaspberryPi when the Network is not Reachable

Hi everyone,

I’ve had a bit of an issue recently with my RaspberryPi disconnecting when I’m flooding the network with camera images. Unfortunately I’m using a dodgy TP-Link WiFi range extender and it doesn’t handle the load well at all.

The issue with this is that it means I cannot connect to the RaspberryPi to safely shut it down. I can switch off the power but this risks corrupting the SD card. In order to get around this I added a script to automatically shutdown when the Pi cannot reach my server for 30 seconds (with help from Co-Pilot!).

target_ip="192.168.0.1"  # Replace with your target IP address
ping_timeout=30           # Timeout in seconds
while true; do
    if ping -c 1 -W $ping_timeout $target_ip >/dev/null; then
        echo "Target IP is reachable."
    else
        echo "Target IP is not reachable. Initiating shutdown..."
        sudo shutdown -h now  # Change to "poweroff" if "shutdown" is not available
    fi
    sleep 1
done

To use the script:

  • 1. Open a text editor and paste the script into a new file.
  • 2. Replace the target_ip variable with the IP address you want to monitor.
  • 3. Save the file with a .sh extension (e.g., shutdown_script.sh).
  • 4. Open a terminal and navigate to the directory where you saved the script.
  • 5. Make the script executable by running the following command: chmod +x shutdown_script.sh.
  • 6. Run the script using the following command: ./shutdown_script.sh.

The script will continuously ping the target IP address every second. If the target IP becomes unreachable for 30 seconds, it will shutdown the pi. You might need to run the script with root privileges (sudo) to execute the shutdown command successfully.

To test it I pointed the script at a VM on my main computer and then paused the VM.

chris@robot1:~/robot_ws/src/my_bot$ sudo ./auto_shutdown.sh
[sudo] password for chris: 
Target IP is reachable.
...
Target IP is reachable.
Target IP is reachable.
Target IP is not reachable. Initiating shutdown...

I then tried pinging the Pi from my main computer to confirm it had shutdown:

Chris@Chriss-Mini-8 Journal % ping 192.168.0.123
PING 192.168.0.123 (192.168.0.123): 56 data bytes
ping: sendto: Host is down
ping: sendto: Host is down