插件窝 干货文章 Linux中设置SSH无密码安全登录详解 - 密钥认证配置指南

Linux中设置SSH无密码安全登录详解 - 密钥认证配置指南

Linux中设置SSH无密码安全登录详解

一、SSH无密码登录原理

SSH(Secure Shell)无密码登录基于非对称加密技术,通过公钥/私钥对实现安全认证:

  • 公钥:存储在远程服务器的~/.ssh/authorized_keys文件中
  • 私钥:保存在本地客户端,需严格保密

二、详细配置步骤

1. 生成密钥对

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
# -t 指定密钥类型(推荐rsa/ed25519)
# -b 指定密钥长度
# -C 添加注释标识

2. 上传公钥到服务器

ssh-copy-id -i ~/.ssh/id_rsa.pub username@remote_host
# 或手动复制:
cat ~/.ssh/id_rsa.pub | ssh user@host "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

3. 设置权限(关键安全步骤)

chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
chmod 600 ~/.ssh/id_rsa  # 私钥文件权限

4. 禁用密码登录(增强安全)

编辑服务器/etc/ssh/sshd_config:

PasswordAuthentication no
PubkeyAuthentication yes
然后重启服务:systemctl restart sshd

三、高级配置技巧

1. 多密钥管理

创建config文件管理不同主机:

Host myserver
    HostName server_ip
    User username
    IdentityFile ~/.ssh/custom_key
    Port 2222

2. 密钥加密保护

ssh-keygen -p -f ~/.ssh/id_rsa  # 为现有密钥添加密码

3. 双因素认证组合

结合Google Authenticator实现二次验证

四、故障排查

  • 检查/var/log/secure日志
  • 客户端加-vvv参数显示调试信息
  • 确认SELinux状态:getenforce

五、安全最佳实践

  1. 定期轮换密钥(建议每3-6个月)
  2. 使用ED25519算法:ssh-keygen -t ed25519
  3. 配置SSH超时:ClientAliveInterval 300
  4. 限制IP访问:AllowUsers user@192.168.1.*