前言

SSH 密钥认证比密码认证更安全、更方便。本文介绍完整的配置流程。

生成密钥对

使用 Ed25519(推荐)

1
ssh-keygen -t ed25519 -C "your_email@example.com"

Ed25519 是目前最推荐的算法:密钥短、速度快、安全性高。

使用 RSA(兼容性更好)

1
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

查看生成的密钥

1
2
3
ls -la ~/.ssh/
# id_ed25519      - 私钥(保密)
# id_ed25519.pub  - 公钥(可公开)

部署公钥到服务器

方法一:ssh-copy-id

1
ssh-copy-id user@server.example.com

这是最简单的方法,会自动将 ~/.ssh/id_ed25519.pub 添加到服务器的 ~/.ssh/authorized_keys

方法二:手动复制

1
2
3
4
5
6
# 在本地查看公钥
cat ~/.ssh/id_ed25519.pub

# 在服务器上添加
echo "ssh-ed25519 AAAAC3Nz... your_email@example.com" >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys

测试连接

1
ssh -v user@server.example.com

-v 参数显示详细日志,方便排查问题。

优化配置

编辑本地 ~/.ssh/config

1
2
3
4
5
Host myserver
    HostName server.example.com
    User your_username
    IdentityFile ~/.ssh/id_ed25519
    ServerAliveInterval 60

之后只需 ssh myserver 即可连接。

禁用密码登录(服务器端)

编辑 /etc/ssh/sshd_config

1
2
PasswordAuthentication no
PubkeyAuthentication yes

重启 SSH 服务:

1
sudo systemctl restart sshd

注意: 确保密钥登录测试成功后再禁用密码登录,否则可能无法登录!

小结

SSH 密钥认证配置步骤:生成密钥 → 部署公钥 → 测试连接 → 优化配置。推荐使用 Ed25519 算法。