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 BashPowerShell,命令相同。
  • PuTTY 用户需用 PuTTYgen 生成密钥。

二、配置公钥到服务器

自动方式(推荐)

ssh-copy-id user@remote_server_ip

手动方式

  1. 本地复制公钥内容:cat ~/.ssh/id_rsa.pub
  2. 登录服务器,编辑:

    nano ~/.ssh/authorized_keys
    
  3. 粘贴公钥,保存退出。
  4. 设置权限:

    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
Copyright © https://yan-jian.com 2023 all right reserved更新时间: 2025-12-29 18:52:33

results matching ""

    No results matching ""