Skip to content

Instantly share code, notes, and snippets.

@rezazoom
Created August 16, 2026 07:55
Show Gist options
  • Select an option

  • Save rezazoom/5ad8dd155bbba4dd7892e169723695ea to your computer and use it in GitHub Desktop.

Select an option

Save rezazoom/5ad8dd155bbba4dd7892e169723695ea to your computer and use it in GitHub Desktop.
Go SSH CLI Helper
#!/bin/bash
# Define colors for styling
GREEN='\033[0;32m'
CYAN='\033[0;36m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
RESET='\033[0m'
# Check if the SSH config file exists
CONFIG_FILE=~/.ssh/config
if [[ ! -f $CONFIG_FILE ]]; then
echo -e "${RED}Error: SSH config file not found at $CONFIG_FILE${RESET}"
exit 1
fi
# Check if tmux is installed
if ! command -v tmux &> /dev/null; then
echo -e "${RED}Error: tmux is not installed. Please install it to use this script.${RESET}"
exit 1
fi
# Extract hostnames, IPs, and add an empty line between each host
hosts_with_empty_lines=$(awk '
/^Host /{host=$2; next} # Capture Host name
/Hostname /{ip=$2; print host " (" ip ")"; host=""; next} # Print host with IP if available
host {print host; host=""; next} # Print host only if no IP
' "$CONFIG_FILE")
# Check if any hosts were found
if [[ -z "$hosts_with_empty_lines" ]]; then
echo -e "${RED}No hosts found in SSH config file.${RESET}"
exit 1
fi
# Use fzf to select multiple hosts with empty lines displayed
echo -e "${CYAN}Available hosts:${RESET}"
selected_hosts=$(echo "$hosts_with_empty_lines" | fzf --multi --prompt="Select hosts to SSH into: " --header="Use Tab to select multiple hosts" --border --layout=reverse-list | grep -v '^$')
# Check if any hosts were selected
if [[ -z "$selected_hosts" ]]; then
echo -e "${RED}No hosts selected.${RESET}"
exit 1
fi
# Count the number of selected hosts
selected_count=$(echo "$selected_hosts" | wc -l)
# If only one host is selected, SSH directly; otherwise, use tmux
if [[ "$selected_count" -eq 1 ]]; then
# Extract the single host
host=$(echo "$selected_hosts" | awk '{print $1}')
echo -e "${YELLOW}Connecting directly to ${GREEN}$host${YELLOW}...${RESET}"
ssh "$host"
else
# Multiple hosts selected, create a new tmux session
session_name="ssh_session"
tmux new-session -d -s "$session_name"
echo -e "${YELLOW}Connecting to selected hosts in tmux session '$session_name'...${RESET}"
window_index=1
while IFS= read -r host_line; do
host=$(echo "$host_line" | awk '{print $1}')
echo -e "${YELLOW}Connecting to ${GREEN}$host${YELLOW} in tmux window $window_index...${RESET}"
# Open a new tmux window for each host
tmux new-window -t "$session_name:$window_index" -n "$host" "ssh $host; exec bash"
((window_index++))
done <<< "$selected_hosts"
# Attach to the tmux session
tmux attach-session -t "$session_name"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment