当 rsync 完成并且没有用户登录时,如何编写脚本来让远程服务器关闭主机?

当 rsync 完成并且没有用户登录时,如何编写脚本来让远程服务器关闭主机?

这是我目前所拥有的。此脚本将在执行 DHCP 等操作的网络服务主机上运行……并且在这种情况下应该唤醒和休眠计算机以进行备份。

#!/bin/bash

## This script exists to wake up the Digital Audio Workstation (DAW) and the NAS on which its session files and other data exists so that the DAW may run its own rsync localbackup script.
## The script pauses between WOL packets because we want to give the NAS time to wake up so that the DAW can mount one of it's shares when it wakes up.
## This script also shuts down the hosts if the condition is met that no human users are logged into the DAW.
## This script is called daily by cron in <cite path and name of cron file here>

## wake the hosts
etherwake -b -i eth0 11:22:33:44:55:66
sleep 10m
etherwake -b -i eth0 22:33:44:55:66:77

## wait for 15 minutes for the backup to complete then check rsync is nolonger running and shutdown the hosts if no users are logged in
sleep 15m
while [ tail rsync on remote host (DAW) for exit code 0 ] && [ -n "$(who)" ] ;do
sleep 1m
done
<send shutdown signal to remote host>

答案1

通过 SSH 连接时测试用户缺席永远不会表明没有用户,因为运行它时您已登录。更简单的解决方案是在执行 rsync 的同一脚本中执行关机。在末尾添加类似以下内容的内容:

while true; do
  [ -z "$(who)" ] && /sbin/poweroff
done

如果机器在无人登录时不需要开机,则只需在备份后将其关闭即可。如果您不想在白天关机,以免人们浪费时间启动它,请检查带有日期的时间:

while true; do
  [ -z "$(who)" ] && [ "$(date +%k)" -lt 5 ] && /sbin/poweroff
done

日期选项+%k返回当前小时数(0-24)。如果备份在 12:00 AM 至 5:00 AM 之间完成,则上述示例将关闭。

相关内容