我通过@Rabid 对脚本进行了一些更改,以添加对多台PC 的支持。
它还检查在 ARP 中找到的条目是否将其标志设置为 0x2 ( =~ active ),因为对我来说,在 PC 离线后,ARP 条目将保持列出太长时间。
#!/bin/bash
# This script is made to be run on an DD- / Open-WRT device to automatically wake a NAS
# server if client PCs are online
# Settings
# Addresses of NAS that gets woken / put to sleep
MACofNAS="MA:CA:DD:RE:SS:00"
IPofNAS="192.168.2.1"
BroadcastAddress="192.168.2.255"
WOLPort=9
# Location of SSH Private Key on WRT (if used for login)
SSHPrivateKeyFile=~/.ssh/id_rsa
# MAC addresses of PCs of which the online status will be checked
PCs=(
"MA:CA:DD:RE:SS:00" # PC1
"MA:CA:DD:RE:SS:00" # PC2
"MA:CA:DD:RE:SS:00" # PC3
"MA:CA:DD:RE:SS:00" # PC4
)
# Determine if any PCs are on
SomePCisON=false
for index in ${!PCs[@]}; do
# Try to detect PC's MAC address in ARP
## Look for all entries in ARP ...
# PCFound=$(grep -o "${PCs[index]}" /proc/net/arp)
# ... OR look only for entries with flag set to 0x2 ( ~ active )
PCFound=$(grep "0x2" /proc/net/arp | grep -o "${PCs[index]}")
# If MAC address is found, the PC must be ON
if [[ ${PCFound} ]]; then
echo "PC ${PCs[index]} is ON"
SomePCisON=true
else
echo "PC ${PCs[index]} is OFF"
fi
done
if [[ "$SomePCisON" == true ]]; then
echo "Some PCs are turned ON"
else
echo "All PCs are turned OFF"
fi
# Check if NAS is ON
if ping -c 1 $IPofNAS > /dev/null; then
echo 'NAS is ON'
NASisON=true
else
echo 'NAS is OFF'
NASisON=false
fi
# If NAS is ON, but all PCs are OFF, put NAS to Sleep
if [[ "$NASisON" == true ]]; then
# If no PCs are ON, put NAS to sleep
if [[ "$SomePCisON" == false ]]; then
echo 'All Hosts Offline'
echo 'Suspending NAS'
# Log in with password (as in @Rabid's script, didn't work for me) ...
DROPBEAR_PASSWORD='NASPASSWORD' ssh root@IPADDRESSOFNAS pm-suspend &
## ... OR log in with authentication key
# ssh -i $SSHPrivateKeyFile root@$IPADDRESSOFNAS pm-suspend &
fi
# If NAS is OFF and any PCs are ON, wake NAS
elif [[ "$SomePCisON" == true ]]; then
# Use wol package on DD-WRT ...
echo 'Waking NAS from LAN, Broadcasting to '$BroadcastAddress\
'on port '$WOLPort' for '$MACofNAS
/usr/sbin/wol -i $BroadcastAddress -p $WOLPort $MACofNAS
/usr/sbin/wol -i $BroadcastAddress -p $WOLPort $MACofNAS;
## ... OR use etherwake package on Open-WRT
## ( Install with: opkg update && opkg install etherwake )
# echo 'Waking NAS from LAN, '$MACofNAS
# /usr/bin/etherwake $MACofNAS
# /usr/bin/etherwake $MACofNAS
fi
要使用身份验证密钥登录,请制作密钥对并将公钥放在 NAS:~/.ssh/authorized_keys 中:
在 WRT 上(使用 Dropbear):
mkdir -p ~/.ssh
# Generate a private key and store it in ~/.ssh/id_rsa
dropbearkey -t rsa -f ~/.ssh/id_rsa
# Store the public key in ~/.ssh/id_rsa.pub
dropbearkey -t rsa -f ~/.ssh/id_rsa -y | grep ssh > ~/.ssh/id_rsa.pub
# Copy id_rsa.pub from WRT:~/.ssh/ to NAS:~/.ssh/
scp ~/.ssh/id_rsa.pub root@nas:~/.ssh/OpenWRT.pub
在 NAS(使用 OpenSSH)上:
# Back up the authorized_keys
cp ~/.ssh/authorized_keys ~/.ssh/authorized_keys_Backup
# Add the new public key to authorized_keys
cat ~/.ssh/OpenWRT.pub >> ~/.ssh/authorized_keys