Created
December 25, 2018 11:08
-
-
Save lschuermann/9518e1c7d3ba8dcfc565fa6f60ab0b8f to your computer and use it in GitHub Desktop.
ssh-srv
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Source: https://gist.githubusercontent.com/solidsnack/d1ba54ac43d79b61f749863cfa3354ab/raw/b7396b4b791f882fd243cee512fbc301bcd6d688/ssh-srv | |
set -o errexit -o nounset -o pipefail | |
function --help { | |
cat <<USAGE | |
USAGE: ssh-srv <DNS name> <SSH options and args>* | |
Allows SSH to nodes referenced by SRV records. The SRV records can be | |
referenced in a "plain style": | |
service.example.com | |
or a "full style": | |
_x._y.service.example.com | |
If referenced in "plain style", \`ssh-srv\` searches for: | |
_*._*.service.example.com | |
The hostnames are sorted and deduplicated and then each host is connected to | |
in sequence. | |
USAGE | |
} | |
tmp= | |
function main { | |
local failures=() names=() user="$1" dns="$2" ; shift ; shift | |
names=( $(lookup "$dns") ) | |
if [[ ! -t 0 ]] | |
then buffer_cmd_stream | |
fi | |
if [[ ${#names[@]} -le 0 ]] | |
then | |
echo "No hosts under: $dns" >&2 | |
exit 2 | |
fi | |
for hostport in "${names[@]}" | |
do | |
if connect "$user@$(echo $hostport | cut -d "," -f2)" -p "$(echo $hostport | cut -d "," -f1)" "$@" | |
then : | |
else | |
echo "Non-zero exit ($?) on: $hostname" >&2 | |
failures+=( "$hostname" ) | |
fi | |
done | |
if [[ ${#failures[@]} -gt 0 ]] | |
then echo "Non-zero exits: ${failures[@]}" >&2 | |
fi | |
exit ${#failures[@]} | |
} | |
function lookup { | |
local dns="$1" | |
case "$dns" in | |
_*._*.*) : ;; # Matches _http._tcp and other SRV specifiers | |
*) dns="_*._*.$dns" ;; | |
esac | |
OUTPUT="$(dig +short "$dns" SRV | head -n 1 | cut -d " " -f3- | sed 's/[.]$//' | sed 's/ /,/g')" | |
echo $OUTPUT | |
} | |
function connect { | |
if [[ ${#tmp} -gt 0 ]] | |
then ssh "$@" < "$tmp" | |
else ssh "$@" | |
fi | |
} | |
function buffer_cmd_stream { | |
tmp="/tmp/ssh-srv~$(whoami)/$$.$(token)" | |
mkdir -p "$(dirname "$tmp")" | |
trap 'rm -rf $tmp' EXIT | |
cat > "$tmp" | |
} | |
function token { | |
printf '%04x' "$RANDOM" "$RANDOM" | |
} | |
case "${1:-}" in | |
-h|--help) --help ;; | |
*) main "$@" ;; | |
esac | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment