Skip to content

Instantly share code, notes, and snippets.

@yaronuliel
Last active August 24, 2022 09:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yaronuliel/807bc83cbd1dd909fae982f6e1c97b28 to your computer and use it in GitHub Desktop.
Save yaronuliel/807bc83cbd1dd909fae982f6e1c97b28 to your computer and use it in GitHub Desktop.
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
cd ~/.ssh
function get_includes {
includes=$(cat $1 | awk '{$1=$1};1' | grep -i "^include\s" | perl -pe 's#^include\s+##i')
for config in $includes; do
echo $config
get_includes $config
done
}
function get_configs {
base=$1
echo $base
get_includes $base
}
function get_hosts {
config_files=$(get_configs ~/.ssh/config)
cat $config_files | awk '{$1=$1};1' | grep -i "^host\s" | perl -pe 's#^host\s+##i' | grep -v \*
}
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