As resource efficiency becomes a priority, many administrators need to reduce server energy consumption. This is especially relevant for test environments, backup systems and home servers that do not need to run around the clock. The challenge is balancing energy savings with access to the system. How can a Debian server sleep outside working hours, wake on a schedule to perform tasks and still be woken for remote SSH access? This article presents a practical approach to flexible server power management.
1. Install the required packages
sudo apt update
sudo apt install ethtool wakeonlan rtcwake2. Configure Wake-on-LAN (WoL) for enp2s0
Check whether your network adapter supports WoL:
sudo ethtool enp2s0 | grep Wake-onEnable WoL:
sudo ethtool -s enp2s0 wol gCreate a service to preserve the WoL settings:
Create the file /etc/systemd/system/wol-enp2s0.service:
[Unit]
Description=Configure Wake-on-LAN for enp2s0
After=network.target
[Service]
Type=oneshot
ExecStart=/sbin/ethtool -s enp2s0 wol g
RemainAfterExit=yes
[Install]
WantedBy=multi-user.targetEnable the service:
sudo systemctl enable wol-enp2s0.service
sudo systemctl start wol-enp2s0.service3. Configure automatic wake-up
Create the script /usr/local/bin/sleep_server.sh:
#!/bin/bash
# Активируем WoL перед сном
/sbin/ethtool -s enp2s0 wol g
# Устанавливаем следующее пробуждение на 3:00
rtcwake -m no -l -t $(date -d "tomorrow 03:00" +%s)
# Переводим сервер в сон (S3 - Suspend to RAM)
echo "Перевод сервера в сон до 3:00..." >> /var/log/sleep_server.log
date >> /var/log/sleep_server.log
systemctl suspendMake the script executable:
sudo chmod +x /usr/local/bin/sleep_server.sh4. Create a script to run tasks at 03:00
Create /usr/local/bin/daily_task.sh:
#!/bin/bash
# Логируем пробуждение
echo "$(date): Сервер проснулся по расписанию" >> /var/log/daily_tasks.log
# ВАШИ ЗАДАЧИ ЗДЕСЬ
# Например:
# - Резервное копирование
# - Обновление системы
# - Очистка логов
# - Запуск отчетов
# Пример задач:
echo "$(date): Начало выполнения задач" >> /var/log/daily_tasks.log
# Выполните команды которые нужны
# apt update && apt upgrade -y
# /путь/к/вашему/скрипту.sh
echo "$(date): Задачи выполнены, готовимся ко сну" >> /var/log/daily_tasks.log
# Активируем WoL снова
/sbin/ethtool -s enp2s0 wol g
# Планируем следующее пробуждение на 3:00 следующего дня
rtcwake -m no -l -t $(date -d "tomorrow 03:00" +%s)
# Возвращаемся в сон
systemctl suspendMake the script executable:
sudo chmod +x /usr/local/bin/daily_task.sh5. Configure systemd to manage sleep
Create a sleep service /etc/systemd/system/go-to-sleep.service:
[Unit]
Description=Перевод сервера в сон
After=network.target
[Service]
Type=oneshot
ExecStart=/usr/local/bin/sleep_server.sh
RemainAfterExit=no
User=root
[Install]
WantedBy=multi-user.targetCreate a timer for daily wake-up /etc/systemd/system/wakeup.timer:
[Unit]
Description=Пробуждение сервера в 3:00
[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true
[Install]
WantedBy=timers.targetCreate a service to run tasks on wake-up /etc/systemd/system/wakeup.service:
[Unit]
Description=Выполнение задач при пробуждении
[Service]
Type=oneshot
ExecStart=/usr/local/bin/daily_task.sh
User=rootEnable the timer:
sudo systemctl enable wakeup.timer
sudo systemctl start wakeup.timer6. Configure immediate sleep
Create the script /usr/local/bin/sleep_now.sh to put the server to sleep manually:
#!/bin/bash
echo "Активация WoL на enp2s0..."
/sbin/ethtool -s enp2s0 wol g
echo "Установка пробуждения на 3:00..."
rtcwake -m no -l -t $(date -d "tomorrow 03:00" +%s)
echo "Переход в сон..."
systemctl suspendMake it executable:
sudo chmod +x /usr/local/bin/sleep_now.sh7. Check SSH activity
Create the script /usr/local/bin/check_and_sleep.sh:
#!/bin/bash
# Текущий час
HOUR=$(date +%H)
# Если время между 3:01 и 23:59
if [ $HOUR -gt 3 ] && [ $HOUR -lt 24 ]; then
# Проверяем активные SSH сессии
ACTIVE_SSH=$(who | grep -c pts)
if [ $ACTIVE_SSH -eq 0 ]; then
# Нет активных SSH сессий - можно спать
echo "$(date): Нет активных SSH сессий, переходим в сон" >> /var/log/sleep_check.log
/usr/local/bin/sleep_now.sh
else
echo "$(date): Найдено активных SSH сессий: $ACTIVE_SSH" >> /var/log/sleep_check.log
fi
fiAdd this to crontab (sudo crontab -e):
# Проверка каждые 5 минут, можно ли усыпить сервер
*/5 * * * * /usr/local/bin/check_and_sleep.sh8. Set up the log files
sudo touch /var/log/sleep_server.log
sudo touch /var/log/daily_tasks.log
sudo touch /var/log/sleep_check.log
sudo chmod 644 /var/log/sleep*.log /var/log/daily_tasks.log9. Waking the server for SSH access
To wake the server, you need:
- Another computer on the same network with
wakeonlan - The MAC address of the enp2s0 network adapter
Get the MAC address:
ip link show enp2s0 | grep link/ether | awk '{print $2}'To wake the server from another computer:
# Установите wakeonlan на клиенте
sudo apt install wakeonlan
# Отправьте Magic Packet
wakeonlan MAC-ADDRESS
# или
wakeonlan -i IP-ADDRESS MAC-ADDRESS10. Verification and testing
Check WoL:
# Статус WoL
sudo ethtool enp2s0 | grep -A5 Wake-on
# Тестовый сон на 1 минуту
sudo rtcwake -m mem -s 60
# Проверьте запланированное пробуждение
sudo cat /sys/class/rtc/rtc0/wakealarm
# Проверьте, что система поддерживает S3 sleep
cat /sys/power/stateCheck the systemd timers:
# Статус таймеров
sudo systemctl list-timers --all
# Логи служб
sudo journalctl -u wakeup.service
sudo journalctl -u go-to-sleep.service11. Command to put the server to sleep now
sudo /usr/local/bin/sleep_now.sh12. Important BIOS/UEFI settings
- Enter your server's BIOS/UEFI
- Find the power management settings
- Enable:
- Wake-on-LAN
- Resume by PCI-E Device
- Power On By PME
- Save the settings and reboot
- This configuration provides:
- Automatic sleep after 03:00
- Wake-up at 03:00 to run tasks
- Wake-on-LAN for SSH access
- A check for active SSH sessions before sleeping
Automatic sleep management on Debian is more than an energy-saving measure: it is a step toward infrastructure that adapts to actual needs. This approach combines energy efficiency with availability. The server runs when needed, wakes for scheduled tasks and can be woken on demand by an administrator. It can reduce operating costs, extend hardware life and lower heat and noise, which is particularly useful for home labs and small offices. Start adopting these practices to make your servers more economical, environmentally conscious and responsive to your tasks.