SyntaxStudy
Sign Up
Linux / Bash SSH Key Generation and Password-less Login
Linux / Bash Beginner 1 min read

SSH Key Generation and Password-less Login

SSH (Secure Shell) provides encrypted remote access to Linux systems. The SSH protocol supports two authentication methods: password authentication and public-key authentication. Public-key authentication is strongly preferred because it is resistant to brute-force attacks and enables automation without storing passwords. Public-key authentication works by generating a mathematically linked key pair: a private key (kept secret on your local machine) and a public key (placed on the remote server). When you connect, the server sends a challenge encrypted with your public key. Your SSH client decrypts it using your private key, proving identity without transmitting the key itself. The `ssh-keygen` command generates key pairs in various algorithms. The public key is added to `~/.ssh/authorized_keys` on the remote server. The `ssh-copy-id` command automates this process. File permissions on `~/.ssh` must be correct (700 on the directory, 600 on private keys, 644 on public keys) — SSH refuses to use keys with overly permissive permissions as a security measure.
Example
# Generate an Ed25519 key pair (recommended, modern)
ssh-keygen -t ed25519 -C "alice@example.com"
# Prompts:
#   Enter file in which to save the key: ~/.ssh/id_ed25519  (Enter for default)
#   Enter passphrase: (use a strong passphrase)

# Generate RSA key (4096-bit, for compatibility)
ssh-keygen -t rsa -b 4096 -C "alice@example.com"

# View the generated public key
cat ~/.ssh/id_ed25519.pub
# ssh-ed25519 AAAA... alice@example.com

# Copy public key to remote server
ssh-copy-id alice@192.168.1.50
ssh-copy-id -i ~/.ssh/id_ed25519.pub alice@192.168.1.50

# Manual method (if ssh-copy-id is unavailable)
cat ~/.ssh/id_ed25519.pub | ssh alice@192.168.1.50 \
    "mkdir -p ~/.ssh && chmod 700 ~/.ssh && \
     cat >> ~/.ssh/authorized_keys && \
     chmod 600 ~/.ssh/authorized_keys"

# Connect using key authentication
ssh alice@192.168.1.50

# Specify a particular key
ssh -i ~/.ssh/id_ed25519 alice@server.example.com

# Set correct permissions (critical!)
chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_ed25519
chmod 644 ~/.ssh/id_ed25519.pub
chmod 600 ~/.ssh/authorized_keys

# List loaded keys in SSH agent
ssh-add -l

# Add key to SSH agent (avoids re-entering passphrase)
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519