Skip to content

Instantly share code, notes, and snippets.

@Leo-PL
Created July 28, 2021 00:01
Show Gist options
  • Save Leo-PL/6d2ae9e38f29f8beee2148875f2691e2 to your computer and use it in GitHub Desktop.
Save Leo-PL/6d2ae9e38f29f8beee2148875f2691e2 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Simple script to check if remote host behind a jump host is up. If not - wake it up using etherwake.
# Usage: invoke the script through ProxyCommand directive from your ssh_config.
# "nc" must be available on your host. "etherwake" must be available on jump host.
# Example:
# Host <target_hostname>
# ProxyCommand ~/.ssh/ssh-wakeup.sh <jumphost_address> <wol_interface> <wol_mac_address> %h %p
function wait_for_host() {
local host=${1}
local port=${2}
local count=${3}
local tries=0
TIMEOUT_SEC=1
while (( ${tries} < ${count} )); do
if nc -z -w ${TIMEOUT_SEC} ${host} ${port} &>/dev/null; then
return 0
fi
tries=$((tries+1))
done
return 1
}
function wakeup_host() {
local router=${1}
local iface=${2}
local mac=${3}
ssh -o BatchMode=yes ${router} etherwake -i ${iface} ${mac} &>/dev/null
}
function main() {
local router=${1}
local iface=${2}
local mac=${3}
local host=${4}
local port=${5}
readonly COUNT_CHECK=3
readonly COUNT_WAIT=300
if ! wait_for_host ${host} ${port} ${COUNT_CHECK}; then
if ! wakeup_host ${router} ${iface} ${mac}; then
return ${?}
fi
if ! wait_for_host ${host} ${port} ${COUNT_WAIT}; then
return 110
fi
fi
exec nc -F ${host} ${port}
}
main "${@}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment