Skip to content

Instantly share code, notes, and snippets.

@ashutoshpw
Created December 28, 2025 07:49
Show Gist options
  • Select an option

  • Save ashutoshpw/cd06af09b95e405b7ae709860a9238a6 to your computer and use it in GitHub Desktop.

Select an option

Save ashutoshpw/cd06af09b95e405b7ae709860a9238a6 to your computer and use it in GitHub Desktop.
#!/bin/bash
set -euo pipefail
# SSH Public Key Setup Script
# Adds SSH public key to authorized_keys, respecting existing keys and preventing duplicates
# Configuration
SSH_KEY="${1:-}"
SSH_USER="${2:-${SUDO_USER:-$USER}}"
SSH_HOME="/home/$SSH_USER"
SSH_DIR="$SSH_HOME/.ssh"
AUTH_KEYS_FILE="$SSH_DIR/authorized_keys"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Helper functions
log_error() {
echo -e "${RED}✗ Error: $1${NC}" >&2
}
log_success() {
echo -e "${GREEN}✓ $1${NC}"
}
log_info() {
echo -e "${YELLOW}ℹ $1${NC}"
}
# Validate input
if [[ -z "$SSH_KEY" ]]; then
log_error "SSH public key not provided"
echo "Usage: $0 '<ssh-public-key>' [username]"
echo "Example: $0 'ssh-rsa AAAA... user@host' ubuntu"
exit 1
fi
# Validate SSH key format
if ! [[ "$SSH_KEY" =~ ^ssh-(rsa|ed25519|ecdsa) ]]; then
log_error "Invalid SSH key format. Expected ssh-rsa, ssh-ed25519, or ssh-ecdsa"
exit 1
fi
log_info "Setting up SSH key for user: $SSH_USER"
# Create .ssh directory if it doesn't exist
if [[ ! -d "$SSH_DIR" ]]; then
log_info "Creating $SSH_DIR"
mkdir -p "$SSH_DIR"
chmod 700 "$SSH_DIR"
chown "$SSH_USER:$SSH_USER" "$SSH_DIR"
else
log_info "$SSH_DIR already exists"
fi
# Create authorized_keys if it doesn't exist
if [[ ! -f "$AUTH_KEYS_FILE" ]]; then
log_info "Creating $AUTH_KEYS_FILE"
touch "$AUTH_KEYS_FILE"
chmod 600 "$AUTH_KEYS_FILE"
chown "$SSH_USER:$SSH_USER" "$AUTH_KEYS_FILE"
fi
# Extract the key fingerprint for comparison (handle comment in key)
KEY_BASE=$(echo "$SSH_KEY" | awk '{print $1 " " $2}')
# Check if key already exists
if grep -qF "$KEY_BASE" "$AUTH_KEYS_FILE"; then
log_info "SSH key already exists in authorized_keys - skipping"
exit 0
fi
# Add the key
log_info "Adding SSH key to $AUTH_KEYS_FILE"
echo "$SSH_KEY" >> "$AUTH_KEYS_FILE"
# Ensure correct permissions
chmod 600 "$AUTH_KEYS_FILE"
chown "$SSH_USER:$SSH_USER" "$AUTH_KEYS_FILE"
log_success "SSH key successfully added!"
log_info "Key type: $(echo "$SSH_KEY" | awk '{print $1}')"
log_info "Total keys in authorized_keys: $(wc -l < "$AUTH_KEYS_FILE")"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment