Managing SSH Agent for Secure Key Handling

Managing SSH Agent for Secure Key Handling

SSH agent provides a secure method for managing private keys in memory, eliminating the need to repeatedly enter passphrases while maintaining security. Proper agent configuration prevents key exposure while enabling convenient authentication.

Start SSH agent and add keys:

# Start SSH agent
eval "$(ssh-agent -s)"

# Add key with timeout (recommended)
ssh-add -t 3600 ~/.ssh/id_ed25519  # Expires after 1 hour

# Add key permanently (use cautiously)
ssh-add ~/.ssh/id_ed25519

# List loaded keys
ssh-add -l

# Remove specific key
ssh-add -d ~/.ssh/id_ed25519

# Remove all keys
ssh-add -D

Implement automatic SSH agent management in your shell profile:

# ~/.bashrc or ~/.zshrc
# SSH Agent Management

# Start agent if not running
if [ -z "$SSH_AUTH_SOCK" ]; then
    eval "$(ssh-agent -s)"
fi

# Function to add keys with confirmation
ssh-add-with-confirm() {
    local key="${1:-$HOME/.ssh/id_ed25519}"
    
    if [ ! -f "$key" ]; then
        echo "Key file not found: $key"
        return 1
    fi
    
    # Check if key already loaded
    if ssh-add -l | grep -q "$(ssh-keygen -lf "$key" | awk '{print $2}')"; then
        echo "Key already loaded: $key"
        return 0
    fi
    
    # Add key with timeout
    echo "Adding SSH key: $key"
    ssh-add -t 7200 "$key"  # 2 hour timeout
}

# Alias for common operations
alias ssh-list='ssh-add -l'
alias ssh-clear='ssh-add -D'
alias ssh-add-default='ssh-add-with-confirm ~/.ssh/id_ed25519'