Automating Shutdowns: Using Poweroff in Scripts and Cron JobsAutomating system shutdowns can save energy, reduce wear on hardware, and enforce maintenance windows. On Unix-like systems (Linux, BSD, etc.), the poweroff command is a standard way to stop the system and turn off power when supported by the hardware. This article explains how poweroff works, safe usage patterns in scripts, scheduling with cron and systemd timers, handling permissions and dependencies, and troubleshooting common pitfalls.
What poweroff does and how it differs from related commands
The poweroff command instructs the init system (systemd, SysV init, OpenRC, etc.) to bring the system down and then power it off. Depending on the distribution and init system, poweroff may be a wrapper for systemctl poweroff, shutdown -h now, or a more direct kernel request.
- Poweroff signals the init system to cleanly stop services and unmount filesystems, then triggers a power-off.
- It is different from reboot (restarts the system) and halt (stops the OS but may not cut power).
- On systemd systems, systemctl poweroff is the recommended interface; poweroff usually maps to it.
When to automate shutdowns
Common use cases:
- Laboratories and classrooms that must power down machines at night.
- Development or build servers that only run during business hours.
- Energy saving in home labs.
- Controlled maintenance windows for hardware updates.
- Remote systems that need scheduled downtime to apply power-cycling policies.
Automated shutdowns should never be used where availability is critical unless paired with careful scheduling, notifications, and fail-safes.
Safety considerations before automating shutdowns
- Ensure no critical jobs or users are active during shutdown. Use checks in scripts to detect running processes, logged-in users, or open network sessions.
- Notify users in advance via wall, write, email, or other messaging systems.
- Ensure filesystems are cleanly unmounted or remounted read-only; let the init system handle this whenever possible.
- Test scripts on non-production machines first.
- Plan for power-loss scenarios: if hardware cannot recover automatically, schedule automatic power-on (BIOS/UEFI Wake-on-RTC) as needed.
- Run shutdown scripts as root or via a properly authorized mechanism (sudo/systemd unit).
Example scripts for safe automated shutdowns
Below are example shell scripts demonstrating common safety checks and invocation of poweroff. Put scripts in /usr/local/sbin or another controlled location, mark executable, and call them from cron or systemd timers.
-
Simple safe-shutdown script (Bash) “`bash #!/bin/bash
/usr/local/sbin/safe-poweroff.sh
Exit on any error
set -euo pipefail
Minimum free space check (in KB)
MIN_ROOT_FREE=1048576 # 1 GB
Check for logged-in users (excluding root)
if who | grep -v ‘^root’ >/dev/null; then echo “Aborting: other users are logged in.” exit 1 fi
Check for long-running processes by name (example: backup)
if pgrep -f ‘backup’ >/dev/null; then echo “Aborting: backup in progress.” exit 1 fi
Check disk free space
root_free=\((df –output=avail / | tail -1 | tr -d ‘ ‘) if [ "\)root_free” -lt “$MIN_ROOT_FREE” ]; then echo “Aborting: insufficient free space on /” exit 1 fi
Send warning to all logged-in users (if any)
echo “System will shut down in 1 minute for scheduled maintenance.” | wall
Give a short delay for warnings to be seen
sleep 60
Final sync and poweroff
sync exec /sbin/poweroff
2) Cron-invokable script that forces shutdown after notifying users ```bash #!/bin/bash # /usr/local/sbin/force-nightly-poweroff.sh wall "Notice: Server will power off in 5 minutes for nightly maintenance." sleep 300 /sbin/poweroff --force
Note: Forcing can skip some cleanups; use carefully.
Scheduling with cron
Cron is a simple, widely available scheduler. Use root’s crontab to run shutdown scripts.
- Edit root’s crontab: sudo crontab -e
- Example: daily shutdown at 23:00 0 23 * * * /usr/local/sbin/safe-poweroff.sh >> /var/log/poweroff.log 2>&1
Tips:
- Redirect output to a log for auditing.
- Use full paths to commands within scripts.
- Cron’s environment is minimal; export PATH or use absolute paths.
- Consider locking (flock) to avoid concurrent runs.
Scheduling with systemd timers (recommended on systemd systems)
Systemd timers are more robust than cron: they respect boot/shutdown ordering, can run missed jobs, and integrate with unit dependencies and logging.
- Create a one-shot service unit to run your script, e.g., /etc/systemd/system/safe-poweroff.service “`ini [Unit] Description=Safe Poweroff Script After=network.target
[Service] Type=oneshot ExecStart=/usr/local/sbin/safe-poweroff.sh
2) Create a timer unit, /etc/systemd/system/safe-poweroff.timer ```ini [Unit] Description=Run safe poweroff daily at 23:00 [Timer] OnCalendar=*-*-* 23:00:00 Persistent=true [Install] WantedBy=timers.target
Enable and start:
- sudo systemctl daemon-reload
- sudo systemctl enable –now safe-poweroff.timer
- Check logs: sudo journalctl -u safe-poweroff.service
Advantages:
- Journal logging, dependency control, and more precise scheduling.
- Persistent=true runs missed jobs if the system was off at the scheduled time.
Using RTC wakeups for scheduled power-on
If you need machines to auto-power on later (for example, power off at night and power on in the morning), configure the hardware RTC/BIOS:
- On Linux, write to /sys/class/rtc/rtc0/wakealarm: echo $(date -d ‘tomorrow 07:00’ +%s) > /sys/class/rtc/rtc0/wakealarm
- Combine with your shutdown script so the machine reboots or powers on at the desired time.
- Many cloud providers and VMs offer separate scheduling APIs.
Permission and security considerations
- Only allow trusted administrators to schedule or run shutdown scripts.
- Use sudoers rules to permit specific scripts to run without a full root shell: username ALL=(root) NOPASSWD: /usr/local/sbin/safe-poweroff.sh
- Protect scripts and logs with appropriate file permissions (root-owned, mode 700 or 750 as appropriate).
- Avoid exposing forced shutdown options via web interfaces without authentication and audit logging.
Handling edge cases and failure modes
- What if poweroff hangs? Use a watchdog or systemd KillMode/TimeoutSec settings. Example in the service unit: TimeoutStartSec=300
- If critical updates must finish, add checks for package manager locks (apt/dpkg/yum) before shutting down.
- For distributed systems, coordinate shutdowns (use cluster-aware tools) to prevent split-brain or data loss.
- Ensure UPS integration for graceful shutdowns during power failures—apcupsd and nut can trigger shutdown scripts.
Troubleshooting common problems
- Poweroff returns immediately but machine doesn’t power off: check ACPI support and BIOS settings; use systemctl poweroff -i to ignore inhibitors.
- Filesystem errors after reboot: make sure unmounts completed; avoid forced poweroffs unless necessary.
- Cron jobs not running: check MAIL output, PATH, crontab ownership, and that cron daemon is active.
- Timers not firing: sudo systemctl list-timers, ensure timer is enabled and systemd daemon reloaded.
Example: full workflow for a classroom lab
- Create safe-poweroff.sh with checks for logged-in students and running lab VMs.
- Configure /etc/systemd/system/safe-poweroff.service and safe-poweroff.timer for 22:30 nightly.
- Configure notification: use wall and email via postfix or local MTA.
- Test on a subset of machines, validate journal logs, and confirm RTC wake alarm if machines must resume in the morning.
Summary
Automating shutdowns with poweroff is straightforward but requires care: verify no critical processes are running, notify users, and prefer systemd timers over cron on modern Linux systems for better integration and logging. Use scripts with safety checks, set proper permissions, and test thoroughly before deploying in production.
If you want, I can: provide a ready-to-deploy script tailored to your distro, create systemd unit files for you, or convert the examples into an Ansible playbook.
Leave a Reply