Copy an SSH Key to Remote Servers (Linux and Windows)
Generate the key pair (if you don't have one)
ssh-keygen -t ed25519 -C "identifying_comment"
# Creates ~/.ssh/id_ed25519 (private) and ~/.ssh/id_ed25519.pub (public)
Only the public key (.pub) goes to the server. Never share the private one.
From Linux / macOS
ssh-copy-id (recommended):
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server
Manual:
cat ~/.ssh/id_ed25519.pub | ssh user@server \
"mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
From Windows (PowerShell)
$pubKey = Get-Content "$env:USERPROFILE\.ssh\id_ed25519.pub"
ssh user@server "mkdir -p ~/.ssh && chmod 700 ~/.ssh && echo '$pubKey' >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
With Git Bash or WSL you can use ssh-copy-id like on Linux.
Test: ssh -i ~/.ssh/id_ed25519 user@server should log in without a password.
Many servers at once
#!/bin/bash
# deploy_key.sh - copy the public key to several servers
KEY="$HOME/.ssh/id_ed25519.pub"
USER_NAME="admin"
SERVERS=(
"192.168.1.10"
"192.168.1.11"
"srv-web01.domain.local"
)
for HOST in "${SERVERS[@]}"; do
echo "-> Copying to $HOST..."
ssh-copy-id -i "$KEY" "$USER_NAME@$HOST" && echo "OK" || echo "FAILED: $HOST"
done
chmod +x deploy_key.sh && ./deploy_key.sh
Permissions on the server
Wrong permissions are the most common reason SSH ignores authorized_keys:
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
chown -R $USER:$USER ~/.ssh
Quick troubleshooting
| Symptom | Likely cause |
|---|---|
| Still asks for a password | Wrong permissions on ~/.ssh or authorized_keys |
Permission denied (publickey) |
Key not copied or wrong user |
Works with -i but not without |
Key not in ~/.ssh/config or not loaded in the agent |
Debug with:
ssh -vvv user@server 2>&1 | grep -E "key|auth|permission"
Bonus: ~/.ssh/config
Host srv-web
HostName 192.168.1.10
User admin
IdentityFile ~/.ssh/id_ed25519
Host srv-db
HostName 192.168.1.11
User dbadmin
IdentityFile ~/.ssh/id_ed25519
Then just ssh srv-web.
Related: SSH key-only login on Ubuntu.