SSH密钥认证标准操作手册
SSH密钥认证标准操作手册
1. 密钥生成
生成ED25519密钥(推荐)
bash
复制
ssh-keygen -t ed25519 -a 100 -C "设备标识/用途说明"
- 参数说明:
-a
:KDF迭代次数(增强密钥保护)-C
:注释信息(建议包含用途标识)
生成RSA密钥(兼容旧系统)
bash
复制
ssh-keygen -t rsa -b 4096 -o -a 100 -C "备份密钥"
2. 公钥部署
自动部署方式
bash
复制
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@host -p 22
手动部署流程
bash
复制
# 本地操作
cat ~/.ssh/id_ed25519.pub | pbcopy # 复制公钥
# 服务器操作
mkdir -p ~/.ssh
echo "粘贴公钥内容" >> ~/.ssh/authorized_keys
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
3. 连接验证
基础连接测试
bash
复制
ssh -i ~/.ssh/id_ed25519 -v user@host
带代理转发
bash
复制
ssh -A -i ~/.ssh/id_ed25519 user@host
4. 客户端配置
~/.ssh/config 示例
conf
复制
Host production
HostName 192.168.1.100
User deploy
Port 2222
IdentityFile ~/.ssh/production_key
IdentitiesOnly yes
ServerAliveInterval 60
Host *
AddKeysToAgent yes
UseKeychain yes
ControlMaster auto
ControlPath ~/.ssh/control-%h-%p-%r
ControlPersist 4h
5. 安全强化
服务端配置 (/etc/ssh/sshd_config)
ini
复制
# 密钥认证配置
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
# 禁用不安全方式
PasswordAuthentication no
ChallengeResponseAuthentication no
UsePAM no
PermitRootLogin no
# 高级保护
MaxAuthTries 3
LoginGraceTime 1m
ClientAliveInterval 300
ClientAliveCountMax 2
重启SSH服务
bash
复制
sudo systemctl restart sshd && sudo systemctl status sshd
6. 权限管理
对象 | 权限 | 命令示例 |
---|---|---|
本地 ~/.ssh | 700 | chmod 700 ~/.ssh |
私钥文件 | 600 | chmod 600 id_ed25519 |
服务器 authorized_keys | 600 | chmod 600 authorized_keys |
服务器 ~/.ssh | 700 | chmod 700 ~/.ssh |
7. 故障排查
常见错误处理
bash
复制
# 调试模式
ssh -vvv -i ~/.ssh/id_ed25519 user@host
# 检查日志
tail -f /var/log/auth.log # Ubuntu/Debian
journalctl -u sshd -f # CentOS/RHEL
# 密钥指纹验证
ssh-keygen -lf ~/.ssh/id_ed25519.pub
8. 最佳实践
-
密钥管理
- 使用密码管理器存储密钥密码
- 每季度轮换生产环境密钥
- 不同服务使用独立密钥对
-
审计监控
bash复制# 查看成功登录记录 sudo grep "Accepted publickey" /var/log/auth.log # 查看失败尝试 sudo grep "Failed publickey" /var/log/auth.log
-
应急措施
bash复制# 临时禁用密钥登录 sudo sed -i 's/PubkeyAuthentication yes/PubkeyAuthentication no/' /etc/ssh/sshd_config sudo systemctl restart sshd