Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Connect to preconfigure ssh hosts (set in ~/.ssh/config) via simple list with numbers or by regex of the host name
#!/usr/bin/env bash
get_hosts="cat ~/.ssh/config | grep Host\\\\s | awk '{ print \$2 }' | sort -u"
if [[ $# -eq 0 ]] ; then
eval "$get_hosts | nl -ba"
exit;
fi
host_num=$1
host=""
re='^[0-9]+$'
if [[ $host_num =~ $re ]] ; then
host=$(eval "$get_hosts | sed -n '${host_num}p'")
if [[ -z $host ]] ; then
echo "Error: invalid host number" >&2
exit 1
fi
fi
# If nothing found yet - try grepping for the result
if [[ -z $host ]]; then
# Partially support glob like * (only after Latin character)
pattern=$(printf $1 | sed 's/\([a-z]\)\*/\1.*/g')
matching_hosts=$(eval "$get_hosts | grep -i $pattern")
lines=$(grep -c . <<<"$matching_hosts")
if (( $lines > 1 )); then
options=$(eval "$get_hosts | nl -s' ' -ba | grep -i \"$pattern\"" | perl -pe 's/^\s*(\d+)\s+(.*)$/\2±(\1)/')
IFS='
'
i=1
for option in $options; do
printf " [%d] %s" $i ${option/±/' '}
echo
((i++))
done
read -p "Select number from the list, or click [Enter] to cancel: " selection
if [[ -z "$selection" ]]; then
exit 1
fi
if [[ $selection =~ $re ]]; then
matching_hosts=$(sed -n "${selection}p" <<<"$options" | awk -F'±' '{print $1}')
fi
fi
host="$matching_hosts"
fi
# Host is Empty
if [[ -z $host ]] ; then
echo "Error: Did not find any matching host" >&2
exit 1
fi
echo "Connecting $host"
ssh $host ${@:2}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment