Thursday, December 22, 2016

Shell script to shut down your PC on power failure

Sometimes you may want to shut down your PC automatically, when there is a  power failure. And you don't have an intelligent UPS or other way to do it. Sometimes it can be like, you want to download a large file and want to reach office soon as possible (today I faced the same problem 😊).

If you are using Linux or Unix based PC with shell support, you can do it simply using the shell script and cron job.

Below is the shell script to shut down the PC, if the modem fails to respond to ping command. Update the IP address with your modem/router IP (get your router IP from Connection information; also update the root password as required and the ping count (4) too; if required.

Create the file pingnshut.sh and add the below code to it and set  permission to execute.
#!/bin/sh
ping -c 4 192.168.1.1
if [ "$?" = 0 ]; then

echo "Power On - `date`"
else
echo "Power Off - `date`"
echo "root_password" | sudo -S poweroff
fi
Then add a job (cron) using the command crontab -e and append the below line to end of the file and save it. This will execute the above script every 5 minutes. Update the shell script path to that of yours.
*/5 * * * * /home/mohammed/Desktop/pingnshut.sh
Change the time (5 minutes), close to your UPS backup time.

To work this fine, ensure your modem is connected to line power, not to any UPS or other power source with battery backup 😝.

No comments:

Post a Comment