bin/gumssh

52 lines
1.5 KiB
Plaintext
Raw Normal View History

2022-12-15 05:47:24 +01:00
#!/usr/bin/env bash
2022-12-15 05:53:37 +01:00
# This script parses the ssh config at ~/.ssh/config to find user@host
# entries, then uses gum choose to select one user@host to ssh into.
# Check for gum.
2022-12-15 05:47:24 +01:00
if ! test -x "$(command -v gum)"; then
echo "Missing dependency: gum"
echo "See github.com/charmbracelet/gum"
exit 1
fi
SSH_CONFIG="${HOME}/.ssh/config"
usern_array=()
hostn_array=()
logins=()
2022-12-15 05:53:37 +01:00
# Read Users from ssh config and store them in usern_array.
2022-12-15 05:47:24 +01:00
while IFS= read -r line; do
if [[ "$line" == *"User"* ]]; then
2023-07-13 06:49:23 +02:00
usern=$(echo "$line" | awk '{ print $2 }')
usern_array+=("$usern")
2022-12-15 05:47:24 +01:00
fi
done < "${SSH_CONFIG}"
2022-12-15 05:53:37 +01:00
# Read HostNames from ssh config and store them in hostn_array.
2022-12-15 05:47:24 +01:00
while IFS= read -r line; do
2023-07-13 06:49:23 +02:00
if [[ "$line" == *"Host "* ]]; then
2022-12-15 05:47:24 +01:00
hostn=$(echo $line | awk '{ print $2 }')
2023-07-13 06:49:23 +02:00
hostn_array+=("$hostn")
2022-12-15 05:47:24 +01:00
fi
done < "${SSH_CONFIG}"
2022-12-15 05:53:37 +01:00
# Set the array_len to the size of usern_array - 1.
2022-12-15 05:47:24 +01:00
let "array_len = ${#usern_array[@]} - 1"
2022-12-15 05:53:37 +01:00
# Iterate through usern_array and hostn_array and match user and host
# pairs, then store them in the logins array in "user@host" format.
2022-12-15 05:47:24 +01:00
for i in $(seq 0 $array_len); do
userhost=$(printf "%s@%s" "${usern_array[i]}" "${hostn_array[i]}")
2023-07-13 06:49:23 +02:00
logins+=("$userhost")
2022-12-15 05:47:24 +01:00
done
2022-12-15 05:53:37 +01:00
# Print each member of logins array on a new line and pipe to gum choose.
# Store selection.
2022-12-15 05:47:24 +01:00
selection=$(printf "%s\n" "${logins[@]}" | gum choose --limit=1)
2022-12-15 05:53:37 +01:00
# If $selection is non-empty, pass it to the ssh -X command.
2022-12-15 05:47:24 +01:00
if test -n "${selection}"; then
2023-02-14 18:27:05 +01:00
autossh -M 0 "${selection}" -X
2022-12-15 05:47:24 +01:00
fi