Automatically shut down pc connected to router when there is power break down.

When pc is connected to router you can shutdown automatically when there is power break down the theory is write a bash script to ping the router ip "192.168.1.1" when the ping command failed mean the router is off duo to power break down and the bash script shutting down the pc, put this script in the cron job to run in every few minutes.
If the ping command succeeded you can check the internet connection with next part of bash script, you need to ping one of google name servers "8.8.8.8" or Cloudflare 1.1.1.1 or OpenDNS 208.67.222.222 and 208.67.220.220 or DNSResolvers.com DNS servers 205.210.42.205 and 64.68.200.200, if ping failed the script will reboot the pc.

This is the bash script shutauto make it executable and put this script to the /usr/bin or any other place, and create a cron job to run this script every few minutes, if the cron job is added as user the user should have the privilege to shut down the computer otherwise add to cron as root:
#! /bin/bash

    if ! ping -c 1 -w 5 192.168.1.1  &>/dev/null; then 
    	    
       /sbin/shutdown -h now
       echo "vifi is off pc shutdown" | mail -s "No vifi pc shutdown" user@localhost
      
       else 

   if ! ping -c 1 -w 30 8.8.8.8  &>/dev/null; then
     
        /sbin/reboot	   
	echo "internet not working pc is reboot" | mail -s "No net pc reboot" user@localhost
	       
    fi
    fi
     
When the ping failed and pc is shutdown or reboot, the script also send mail to the user, replace the user with your user name.

Shutdown just in power break down:

If you want to shut down the laptop just with the power break down, use this bash script:
#!/bin/bash

    st="$(cat /sys/class/power_supply/AC/online)"
    if [ $st == 0 ] &>/dev/null; then

       /sbin/shutdown -h now

   fi
Make the script executable put in a place and add to the cron job when the power cable is unplugged or the power is down the script will shut down the pc.


<< Previous Next >>