Auto-shutdown a linux machine when nobody is logged in

Sometimes you need a simple, quick and dirty way to auto-shutdown a linux machine when nobody is using it. This is specially true for home lab environments or a cloud environment used mainly for development where it keeping the machines on longer than required is a waste of resources.

The easiest way to achieve it without any fancy management solution is to use a bash script that runs from time to time to check if there is someone logged into it and shutdown it if nobody is logged. This article contains a very simple script that does that and log its activities into the syslog.

The script is supposed to be executed by root so it may be stored at /root/bin/auto-shutdown.sh or anywhere you wish.

#!/bin/bash
LOGGED_USERS=$(who)
if [ -z "$LOGGED_USERS" ]; then
    /usr/bin/logger -t "AUTO_SHUTDOWN" "No users logged in. Automatic shutdown now!"
    /usr/sbin/shutdown -h now
else
    /usr/bin/logger -t "AUTO_SHUTDOWN" "There is at least one user logged in. Automatic shutdown skipped!"
fi

You may use chmod 700 /root/bin/auto-shutdown.sh to mark it as an executable but is is not required.

This script uses the output of who to determine if there is someone logged in. If it returns an empty string, nobody is logged so the machine can be turned off using /usr/sbin/shutdown -h now otherwise it does nothing. In both cases, it uses /usr/bin/logger to register the script's result into syslog in order to make it easier to trace.

This script is supposed to be executed by the root's crontab at regular intervals (e.g. hourly):

0   */1 *   *   *   /bin/bash /root/bin/auto-shutdown.sh

It is important to notice that it is a solution designed to be executed by stand-alone machines with no external management solution installed as most of them will also provide such a trivial feature.