Automatic shutdown of Windows 10 computer from bash script

894 Views Asked by At

I have a problem with my power failure monitoring scheme / automatic shutdown of Windows 10 computer. On my network I have a Linux box that has a UPS unit connected via USB and maintained with software which makes the computer shut down when power failure occurs. On another computer, also powered from the same UPS unit running headless Windows 10 server, I have setup a simple bash script (cygwin) running from Task Scheduler. It is supposed to shutdown this computer once the aforementioned Linux box stops responding to ping on the network (because it shuts down when power failure is detected). The UPS unit is setup to shut the power down after 10 minutes from power failure, giving plenty of time for the Windows machine to detect lack of response from Linux box and executing shutdown. Here is the monitoring script code:

#!/bin/bash

upshost="<linux-box-ip>"

echo "UPS Host: $upshost"
while true
do
    date
    ping -c3 $upshost >/dev/null
    if [[ $? -ne 0 ]]
    then
        echo "WARNING: Ping failed, trying again in 30 seconds ..."
        sleep 30
        ping -c3 $upshost >/dev/null
        [[ $? -eq 0 ]] || break
    fi
    echo "Host $upshost responded to ping."
    sleep 30
done
date
echo "ERROR: Host $upshost didn't respond to ping."
echo "System will shutdown in 1 minute."
shutdown -h +1 "System will shutdown in 1 minute."

NOTE: is the actual IP address of my Linux box which is always the same (reserved in the router setup).

The task scheduler properties:

Runs from SYSTEM account, whether user is logged on or not, with highest privileges.
Triggers: at system startup
Actions: Start a program
program/script -> c:\cygwin64\bin\bash
arguments -> -l -c "/cygdrive/c/bin/pwrwdog.sh > /cygdrive/c/tmp/pwrwdog.trc"
runs in -> c:\cygwin64\bin
Start if any network connection is available.

I see in traces and in task scheduler history that script properly monitors the network response from Linux box, breaks out of the monitoring loop when host stops responding and invokes shutdown command. The problem is - the shutdown doesn't actually happen:

Host <linux-box-ip> responded to ping.
Sun, Jan  3, 2021  7:23:48 AM
Host <linux-box-ip> responded to ping.
Sun, Jan  3, 2021  7:24:20 AM
WARNING: Ping failed, trying again in 30 seconds ...
Sun, Jan  3, 2021  7:25:16 AM
ERROR: Host <linux-box-ip> didn't respond to ping.
System will shutdown in 1 minute.
System will shutdown in 1 minute.

What do I miss?

0

There are 0 best solutions below