Skip to content

Instantly share code, notes, and snippets.

@lbogdan
Last active September 1, 2018 11:15
Show Gist options
  • Save lbogdan/c50e74e550bccc5de784bd465f64d6db to your computer and use it in GitHub Desktop.
Save lbogdan/c50e74e550bccc5de784bd465f64d6db to your computer and use it in GitHub Desktop.
shutdown on lan
#!/bin/bash
INTERFACE=ens33 # interface we're listening on
NUM_PACKETS=3 # number of packets sent at once
TIME_THRESHOLD=3 # max seconds between packets
PACKET_THRESHOLD=3 # packets needed to run command
COMMAND="echo DONE!" # command to run
packet_count=0
last_timestamp=0
# parse ifconfig output:
# ens33 Link encap:Ethernet HWaddr 00:0c:29:a1:6a:27
[[ $(ifconfig "$INTERFACE") =~ HWaddr[[:space:]](.{17}) ]]
# matched MAC address
mac="${BASH_REMATCH[1]}"
# transform MAC address to regex for ngrep by replacing all : with \x
# i.e. 00:11:22:33:44:55 to \x00\x11\x22\x33\x44\x55
mac_regex="\x${mac//:/\\x}"
while true; do
# wait for NUM_PACKETS wol packets addressed to our MAC address on UDP port 9
ngrep -d "$INTERFACE" -n "$NUM_PACKETS" -q -x "\xff{6}($mac_regex){16}" "udp and dst port 9" >/dev/null 2>&1
# got'em, check time difference from last packet
timestamp=$(date +%s)
if [ "$last_timestamp" -ne "0" ]; then # $last_timestamp != 0
diff=$(($timestamp - $last_timestamp))
if [ "$diff" -le "$TIME_THRESHOLD" ]; then # $diff <= $TIME_THRESHOLD
(( packet_count += 1))
if [ "$packet_count" -eq "$PACKET_THRESHOLD" ]; then # $packet_count == $PACKET_THRESHOLD
echo "$timestamp: packet threshold reached, running \"$COMMAND\""
eval "$COMMAND"
exit 0
else
echo "$timestamp: got packet, count is $packet_count"
fi
else
echo "$timestamp: time threshold exceeded (${diff}s), restarting"
packet_count=1
fi
else
echo "$timestamp: first packet"
packet_count=1
fi
last_timestamp="$timestamp"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment