MacOS – Error when using `sudo shutdown` on remote machine

macossudoterminal

I'm remotely shutting down a bunch of Macs by using ssh to execute the shutdown command on each of them. I've asked the question before (Shutdown "no tty present and no askpass program specified"?) and got it working by adding ADMIN ALL=(ALL) NOPASSWD: /sbin/shutdown -h now to the sudoers files as recommended.

In the meantime two of the remote Macs got upgraded to Sierra and I again get

sudo: no tty present and no askpass program specified

even though the line in the sudoers file is still there.

What do I need to change to make this work with Sierra?

Best Answer

A proper solution for your remote shutdown script is the following:

Script (please adjust the MAX_UPSEC value, for testing purposes I used a low value):

#!/bin/bash
BOOT_TIME=$(sysctl -n kern.boottime | sed -e 's/.* sec = \([0-9]*\).*/\1/')
CURR_TIME=$(date +%s)
MAX_UPSEC=300 #Seconds

SECS_UP=$(($CURR_TIME - $BOOT_TIME))
    if [ $SECS_UP -ge ${MAX_UPSEC} ];then
        echo "Mac is going to shutdown because it is already $SECS_UP seconds running"
        shutdown -h now
    else
        echo "No shutdown needed because the Mac is only $SECS_UP seconds up"
fi

If you run the shutdown script (assuming the script is located at ~/bin/sh/) with the following command:

ssh admusr@host  'sudo bash -s' < /Users/admusr/bin/sh/ShutdownUPTIME.sh

the proper sudoers lines on the remote hosts are then

root        ALL = (ALL) ALL
%admin      ALL = (ALL) ALL
admusr      ALL = (ALL) NOPASSWD: /bin/bash