Skip to content

Instantly share code, notes, and snippets.

@WomB0ComB0
Created September 6, 2025 15:46
Show Gist options
  • Select an option

  • Save WomB0ComB0/c80733ebd03257f52ab33c4cc7be468b to your computer and use it in GitHub Desktop.

Select an option

Save WomB0ComB0/c80733ebd03257f52ab33c4cc7be468b to your computer and use it in GitHub Desktop.
gitssh - Enhanced with AI-generated documentation
#!/bin/bash
# Git Platform SSH Setup Script
# This script sets up SSH keys and known hosts for GitHub, GitLab, and BitBucket
set -e # Exit on any error
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Function to print colored output
print_status() {
echo -e "${BLUE}[INFO]${NC} $1"
}
print_success() {
echo -e "${GREEN}[SUCCESS]${NC} $1"
}
print_warning() {
echo -e "${YELLOW}[WARNING]${NC} $1"
}
print_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
# Check if SSH directory exists, create if not
setup_ssh_dir() {
if [ ! -d "$HOME/.ssh" ]; then
print_status "Creating SSH directory..."
mkdir -p "$HOME/.ssh"
chmod 700 "$HOME/.ssh"
print_success "SSH directory created"
else
print_status "SSH directory already exists"
fi
}
# Generate SSH key if it doesn't exist
generate_ssh_key() {
local key_path="$HOME/.ssh/id_ed25519"
if [ ! -f "$key_path" ]; then
print_status "No SSH key found. Generating new ED25519 key..."
read -p "Enter your email address: " email
ssh-keygen -t ed25519 -C "$email" -f "$key_path" -N ""
print_success "SSH key generated at $key_path"
# Start ssh-agent and add key
eval "$(ssh-agent -s)"
ssh-add "$key_path"
print_success "SSH key added to ssh-agent"
print_warning "Don't forget to add your public key to your Git platforms!"
print_status "Your public key:"
cat "$key_path.pub"
echo ""
else
print_status "SSH key already exists at $key_path"
# Ensure key is added to ssh-agent
if ! ssh-add -l | grep -q "$key_path"; then
eval "$(ssh-agent -s)"
ssh-add "$key_path"
print_success "SSH key added to ssh-agent"
fi
fi
}
# Add known hosts for Git platforms
add_known_hosts() {
local known_hosts_file="$HOME/.ssh/known_hosts"
print_status "Adding known hosts for Git platforms..."
# Platform configurations
declare -A platforms=(
["github.com"]="github.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl"
["gitlab.com"]="gitlab.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAfuCHKVTjquxvt6CM6tdG4SLp1Btn/nOeHHE5UOzRdf"
["bitbucket.org"]="bitbucket.org ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIazEu89wgQZ4bqs3d63QSMzYVa0MuJ2e2gKTKqu+UUO"
)
# Create known_hosts file if it doesn't exist
touch "$known_hosts_file"
chmod 644 "$known_hosts_file"
for platform in "${!platforms[@]}"; do
if ! grep -q "$platform" "$known_hosts_file"; then
echo "${platforms[$platform]}" >> "$known_hosts_file"
print_success "Added $platform to known hosts"
else
print_status "$platform already in known hosts"
fi
done
}
# Test SSH connections
test_connections() {
print_status "Testing SSH connections..."
local platforms=("[email protected]" "[email protected]" "[email protected]")
for platform in "${platforms[@]}"; do
print_status "Testing connection to $platform..."
if ssh -T -o ConnectTimeout=10 "$platform" 2>&1 | grep -q -E "(successfully authenticated|logged in|Welcome)"; then
print_success "Connection to $platform successful"
else
# For these platforms, rejection is actually expected and means auth is working
if ssh -T -o ConnectTimeout=10 "$platform" 2>&1 | grep -q -E "(Permission denied|Hi.*!|Welcome)"; then
print_success "Connection to $platform successful (authentication working)"
else
print_warning "Connection to $platform may have issues"
fi
fi
done
}
# Create or update SSH config
create_ssh_config() {
local ssh_config="$HOME/.ssh/config"
print_status "Setting up SSH config..."
# Backup existing config if it exists
if [ -f "$ssh_config" ]; then
cp "$ssh_config" "$ssh_config.backup.$(date +%Y%m%d_%H%M%S)"
print_status "Backed up existing SSH config"
fi
# Create/update SSH config
cat << EOF > "$ssh_config"
# GitHub
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519
IdentitiesOnly yes
# GitLab
Host gitlab.com
HostName gitlab.com
User git
IdentityFile ~/.ssh/id_ed25519
IdentitiesOnly yes
# BitBucket
Host bitbucket.org
HostName bitbucket.org
User git
IdentityFile ~/.ssh/id_ed25519
IdentitiesOnly yes
# Default settings
Host *
AddKeysToAgent yes
UseKeychain yes
ServerAliveInterval 60
ServerAliveCountMax 30
EOF
chmod 600 "$ssh_config"
print_success "SSH config created/updated"
}
# Main setup function
main() {
print_status "Starting Git platform SSH setup..."
echo ""
setup_ssh_dir
generate_ssh_key
add_known_hosts
create_ssh_config
test_connections
echo ""
print_success "Setup complete!"
print_status "You can now clone repositories without host verification prompts."
print_warning "Make sure to add your public key to your Git platform accounts:"
echo " - GitHub: https://github.com/settings/keys"
echo " - GitLab: https://gitlab.com/-/profile/keys"
echo " - BitBucket: https://bitbucket.org/account/settings/ssh-keys/"
echo ""
print_status "Your public key:"
cat "$HOME/.ssh/id_ed25519.pub"
}
# Run main function
main "$@"

gitssh

File Type: TXT
Lines: 195
Size: 5.5 KB
Generated: 9/6/2025, 11:46:41 AM


Code Analysis: gitssh

This is a Bash script designed to automate the setup of SSH keys and known hosts for interacting with Git platforms like GitHub, GitLab, and Bitbucket. It aims to streamline the process of authenticating with these services via SSH, eliminating manual steps and potential errors.

Key Features and Functionality:

  1. Colorized Output: The script uses ANSI escape codes to provide colorized output, improving readability and highlighting important information (status, success, warnings, errors).

  2. Error Handling: The set -e command ensures that the script exits immediately if any command fails, preventing unexpected behavior.

  3. SSH Directory Setup: The setup_ssh_dir function checks for the existence of the ~/.ssh directory and creates it if it doesn't exist, setting appropriate permissions (700).

  4. SSH Key Generation: The generate_ssh_key function checks for an existing ED25519 SSH key (~/.ssh/id_ed25519). If one doesn't exist, it generates a new key pair, prompting the user for their email address. It then starts ssh-agent, adds the newly generated key, and displays the public key for the user to add to their Git platform accounts. It also ensures the key is added to the agent if it already exists.

  5. Known Hosts Management: The add_known_hosts function adds the SSH host keys for GitHub, GitLab, and Bitbucket to the ~/.ssh/known_hosts file. This prevents "man-in-the-middle" warnings when connecting to these services for the first time. It uses an associative array (declare -A) to store the platform names and their corresponding host keys.

  6. SSH Connection Testing: The test_connections function attempts to establish SSH connections to GitHub, GitLab, and Bitbucket to verify that the SSH configuration is working correctly. It uses ssh -T -o ConnectTimeout=10 to test the connections and checks the output for success messages. It handles the expected "Permission denied" responses from some platforms as successful authentication.

  7. SSH Config Creation/Update: The create_ssh_config function creates or updates the ~/.ssh/config file with specific configurations for GitHub, GitLab, and Bitbucket. This includes specifying the hostname, user (git), and identity file (the generated SSH key). It also includes default settings for all hosts, such as adding keys to the agent, using the keychain, and setting server alive intervals. It backs up the existing config file before overwriting it.

  8. Main Function: The main function orchestrates the entire setup process by calling the individual functions in the correct order. It also provides instructions to the user on how to add their public key to their Git platform accounts.

Architecture and Design:

  • Modular Design: The script is well-structured with separate functions for each task, making it easy to understand, maintain, and extend.
  • Idempotency: Some functions, like setup_ssh_dir, generate_ssh_key, and add_known_hosts, are designed to be idempotent, meaning they can be run multiple times without causing unintended side effects.
  • Configuration via Variables: The script uses variables for colors, file paths, and platform configurations, making it easy to customize.

Practical Usage:

  1. Execution: The script can be executed from the command line using bash gitssh.
  2. Prerequisites: The script requires ssh-keygen, ssh-agent, ssh, grep, cat, mkdir, chmod, cp, touch, and date to be installed on the system.
  3. User Interaction: The script prompts the user for their email address during SSH key generation.
  4. Post-Setup Steps: The script instructs the user to add their public key to their Git platform accounts.

Potential Improvements:

  1. Error Handling: More robust error handling could be implemented, such as checking for the existence of required commands and providing more informative error messages.
  2. Configuration Options: The script could be made more configurable by allowing users to specify the SSH key path, Git platform hostnames, and other settings via command-line arguments or environment variables.
  3. Key Management: The script could provide options for managing existing SSH keys, such as listing them, deleting them, or changing their passphrase.
  4. Security Considerations: The script stores the SSH key passphrase in plain text. Consider using a more secure method for storing the passphrase, such as using a password manager or prompting the user for the passphrase each time the key is used. The script should also warn the user about the importance of protecting their SSH key.
  5. Cross-Platform Compatibility: While the script is written in Bash, it may not be fully compatible with all Unix-like systems. Consider using more portable shell commands or providing alternative implementations for different platforms.
  6. Idempotency: The create_ssh_config function overwrites the existing config file. It could be improved to merge the new configuration with the existing one, preserving any custom settings.
  7. Logging: Add more detailed logging to help troubleshoot issues.
  8. Input Validation: Validate the email address provided by the user.

Summary:

The gitssh script is a useful tool for automating the setup of SSH keys and known hosts for Git platforms. It is well-structured, easy to use, and provides a significant time-saving for developers who frequently work with Git repositories. By addressing the potential improvements outlined above, the script could be made even more robust, flexible, and secure.


Description generated using AI analysis

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment