Skip to content

Instantly share code, notes, and snippets.

@grahamhelton
Last active December 19, 2024 21:12
Show Gist options
  • Save grahamhelton/aac6782e50376a20c2fc33c6109044a8 to your computer and use it in GitHub Desktop.
Save grahamhelton/aac6782e50376a20c2fc33c6109044a8 to your computer and use it in GitHub Desktop.
This script creates a systemd timer that shuts down a machine if there are no active connections to it. Default is 30 minutes. Must run as root.
#!/bin/bash
## Colors
BOLD=$(tput bold)
NOCOLOR=$(tput sgr0)
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW=$(tput setaf 3)
BLUE=$(tput setaf 4)
PURPLE=$(tput setaf 5)
CYAN=$(tput setaf 6)
WHITE=$(tput setaf 7)
BLACK=$(tput setaf 8)
BG_YELLOW=$(tput setab 3)
BOLD_RED=($BOLD$RED)
# Formatting
DIV="$BLACK---------------------------------------------------------------------$NOCOLOR"
TICK="$NOCOLOR[$GREEN+$NOCOLOR] "
TICK_MOVE="$NOCOLOR[$GREEN~>$NOCOLOR]"
TICK_BACKUP="$NOCOLOR[$GREEN<~$NOCOLOR] "
TICK_INPUT="$NOCOLOR[$YELLOW!$NOCOLOR] "
TICK_ERROR="$NOCOLOR[$RED!$NOCOLOR] "
TICK_INFO="$NOCOLOR[$YELLOW-$NOCOLOR] "
# Check if the script is running as root
if [[ $EUID -ne 0 ]]; then
echo $TICK_ERROR"This script must be run as root. Please use sudo."
exit 1
fi
# Create the shutdown script
echo $TICK"Making$BLUE /usr/local/bin/shutdown-if-no-logged-users.sh"$NOCOLOR
cat << 'EOF' > /usr/local/bin/shutdown-if-no-logged-users.sh
#!/bin/bash
#Get the number of logged-in users (excluding root and system users).
loggedInUsers=$(who | grep -v -E 'root|systemd-|dbus' | wc -l)
if [[ $loggedInUsers -eq 0 ]]; then
# No users logged in, shut down the VM.
shutdown -h now
else
echo "Users are logged in"
fi
EOF
# Make the script executable
echo $TICK"Making$BLUE /usr/local/bin/shutdown-if-no-logged-users.sh"$NOCOLOR
chmod +x /usr/local/bin/shutdown-if-no-logged-users.sh
#Create the systemd service file
echo $TICK"Creating$BLUE /etc/systemd/system/are-users-logged.service"$NOCOLOR
cat << 'EOF' > /etc/systemd/system/are-users-logged.service
[Unit]
Description=Check for logged-in users and shutdown if idle
[Service]
Type=oneshot
ExecStart=/usr/local/bin/shutdown-if-no-logged-users.sh
[Install]
WantedBy=multi-user.target
EOF
# Create the systemd timer file
echo $TICK"Creating$BLUE /etc/systemd/system/are-users-logged.timer"$NOCOLOR
cat << 'EOF' > /etc/systemd/system/are-users-logged.timer
[Unit]
Description=Run are-users-logged.service every 30 minutes
[Timer]
OnBootSec=30min
OnUnitActiveSec=30min
[Install]
WantedBy=timers.target
EOF
# Enable and start the timer
echo $TICK"Enabling$BLUE are-users-logged.timer"$NOCOLOR
systemctl enable are-users-logged.timer
echo $TICK"Starting$BLUE are-users-logged.timer"$NOCOLOR
systemctl start are-users-logged.timer
echo $TICK$GREEN"VM shutdown service installed and activated."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment