Deploying Public Keys to Servers

Deploying Public Keys to Servers

Proper public key deployment ensures secure access while maintaining the integrity of the authentication system. The authorized_keys file on each server contains the public keys allowed to authenticate, requiring careful management to prevent unauthorized additions.

The most secure method for initial key deployment uses an existing authenticated connection:

# Using ssh-copy-id (recommended)
ssh-copy-id -i ~/.ssh/id_ed25519.pub [email protected]

# Manual method if ssh-copy-id unavailable
cat ~/.ssh/id_ed25519.pub | ssh [email protected] \
  "mkdir -p ~/.ssh && chmod 700 ~/.ssh && \
   cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"

Verify the deployment succeeded:

ssh -i ~/.ssh/id_ed25519 [email protected]
# Should connect without password prompt (except for key passphrase)

For multiple servers, automate deployment while maintaining security:

#!/bin/bash
# deploy_ssh_key.sh - Deploy SSH key to multiple servers

KEY_FILE="$HOME/.ssh/id_ed25519.pub"
SERVERS=("web01.example.com" "web02.example.com" "db01.example.com")
USER="deploy"

if [ ! -f "$KEY_FILE" ]; then
    echo "Error: Public key file not found: $KEY_FILE"
    exit 1
fi

for server in "${SERVERS[@]}"; do
    echo "Deploying key to $server..."
    ssh-copy-id -i "$KEY_FILE" "$USER@$server" || \
        echo "Failed to deploy to $server"
done