SSH(Secure Shell)是一种网络协议,用于在不安全的网络中提供安全的远程登录和其他网络服务。SSH 密钥认证是一种比传统密码认证更安全的登录方式。
SSH 密钥认证文档如下:
一、密钥生成
Linux/macOS
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
-t rsa:指定密钥类型-b 4096:密钥长度-C:注释,便于识别
默认生成:
- 私钥:
~/.ssh/id_rsa - 公钥:
~/.ssh/id_rsa.pub
Windows
- 使用 Git Bash 或 PowerShell,命令相同。
- PuTTY 用户需用 PuTTYgen 生成密钥。
二、配置公钥到服务器
自动方式(推荐)
ssh-copy-id user@remote_server_ip
手动方式
- 本地复制公钥内容:
cat ~/.ssh/id_rsa.pub 登录服务器,编辑:
nano ~/.ssh/authorized_keys- 粘贴公钥,保存退出。
设置权限:
chmod 700 ~/.ssh chmod 600 ~/.ssh/authorized_keys
三、客户端配置(简化登录)
编辑 ~/.ssh/config:
Host myserver
HostName remote_server_ip
User user
IdentityFile ~/.ssh/id_rsa
登录时只需:
ssh myserver
四、在服务器上生成密钥(用于跳板机或互联)
ssh-keygen -t ed25519 -C "your_email@example.com"
- 推荐使用 ED25519:更快、更安全。
- 默认保存到
~/.ssh/id_ed25519和~/.ssh/id_ed25519.pub。
五、安全加固建议
禁用密码登录(防止暴力破解) 编辑
/etc/ssh/sshd_config:PasswordAuthentication no然后重启:
sudo systemctl restart sshd- 多用户管理 每个用户维护自己的
~/.ssh/authorized_keys。 支持多个公钥并行。 私钥保护
- 不要随意复制或泄露。
- 建议设置 passphrase。
- 使用
ssh-agent管理密钥,避免频繁输入密码。
六、常见问题
登录仍需密码?
- 检查
~/.ssh/authorized_keys权限是否为600。 - 确认
.ssh目录权限为700。 确认
sshd_config中启用了:PubkeyAuthentication yes
- 检查
多个密钥冲突?
- 在
~/.ssh/config中明确指定IdentityFile。 - 或使用
ssh -i /path/to/key user@server_ip。
- 在