So I have this script to shutdown Macs after 24 hours runtime.
#!/bin/bash
my_macs=( Mac1 Mac2 Mac3 )
MAX_UPDAYS=1
CURR_TIME=$(date +%s)
MAX_UPTIME=$(( MAX_UPDAYS * 86400 ))
ADMINUSER="pcpatch"
echo "Remote Shutdown Check vom $(date)" | tee -a /Users/admin/Shutdown/Log/Shutdown 2>&1
for MAC in "${my_macs[@]}"
do
echo -n "Überprüfe ${MAC}... "
if /sbin/ping -q -c3 "${MAC}" >/dev/null; then
echo "${MAC} ist angeschaltet. Laufzeit wird ermittelt... "
BOOT_TIME=0
BOOT_TIME=$(ssh "${ADMINUSER}@${MAC}" sysctl -n kern.boottime | sed -e 's/.* sec = \([0-9]*\).*/\1/')
if [ "$BOOT_TIME" -gt 0 ] && [ $(( CURR_TIME - BOOT_TIME )) -ge $MAX_UPTIME ]; then
echo "${MAC} ist über 24 Stunden online. Shutdown wird ausgeführt!"
ssh "${ADMINUSER}@${MAC}" 'sudo /sbin/shutdown -h now'
else
echo "${MAC} ist noch keine 24 Stunden online. Shutdown wird abgebrochen!"
fi
else
echo "${MAC} ist nicht erreichbar (Ping fehlgeschlagen)"
fi
done | tee -a /Users/pcpatch/Shutdown/Log/Shutdown 2>&1
echo " " | tee -a /Users/pcpatch/Shutdown/Log/Shutdown 2>&1
When I run it through the terminal it works fine, Macs that are online more than 24 hours shut down, everything else does nothing.
So far so good, but I want to run this script through a cronjob everyday at 23:00 o'clock. So I made this cronjob:
00 23 * * * /Users/admin/Shutdown/Shutdown.sh
Now the script runs everyday, the cron line itself works. The Macs won't shutdown though and the log just says that the Macs did not run more than 24 hours. Though I frequently have Macs that run more than 3-4 days.
Does anyone know how to solve this problem?
Edit: I added $BOOT_TIME
and $CURR_TIME
to the log, and it gives out somehing like this: 1492549200
as CURR_TIME
and nothing as the BOOT_TIME
, though the Mac was definitely running, as he is right now (6 days online). This Mac has OSX Sierra installed though and one other Mac (with OS X El Capitan) put BOOT_TIME
as 1492505076
and CURR_TIME
as 1492549200
I really don't know what these number could mean though...
$BOOT_TIME
,$CURR_TIME
and other values of interest, then come back >24h later and add the values to the question.BOOT_TIME
doesn't get set becausessh
(silently) fails. Are you running the cronjob from the same user as you do through Terminal? Or does the cronjob belong toroot
but you manually run it as an admin user?sudo crontab -e
, so I suppose it should be running asroot
I tried it with different users through the terminal though and they both worked (my own admin and with the sudo command)