Linux SSH 密钥登录配置方法

4次阅读

linux ssh密钥登录更安全便捷,通过本地私钥与服务器公钥配对验证;生成ed25519密钥对后上传公钥,配置sshd启用pubkeyauthentication并禁用密码登录,最后重启服务并验证连接。

Linux SSH 密钥登录配置方法

Linux SSH 密钥登录比密码登录更安全、更便捷,核心是用一对密钥(私钥本地保管,公钥上传到服务器)替代明文密码验证。

生成密钥对(本地操作)

在你的本地终端(Linux/macos/WSL)运行以下命令:

  • 执行 ssh-keygen -t ed25519 -C “your_email@example.com”(推荐使用 Ed25519 算法,安全性高、速度快)
  • 按回车接受默认保存路径(通常是 ~/.ssh/id_ed25519),也可自定义文件名
  • 可选:输入一个密钥口令(passphrase),增加私钥本地安全性;直接回车则不设口令

完成后,你会得到两个文件:id_ed25519(私钥,必须保密)和 id_ed25519.pub(公钥,可分发)。

上传公钥到远程服务器

有三种常用方式,推荐前两种:

  • ssh-copy-id(最简单):运行 ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server_ip,自动追加公钥到服务器的 ~/.ssh/authorized_keys
  • 手动复制:用 cat ~/.ssh/id_ed25519.pub 查看公钥内容,再通过已有 SSH 连接登录服务器,将该行内容追加到 ~/.ssh/authorized_keys(注意权限:文件需为 600,目录为 700)
  • 若服务器禁用了密码登录且尚未配置密钥,需先通过其他方式(如控制台、VPS 后台)临时启用密码登录或上传公钥

配置并启用密钥登录(服务器端)

登录服务器后,编辑 SSH 服务配置:

  • 运行 sudo nano /etc/ssh/sshd_config
  • 确认以下几项已启用或设置正确:
    • PubkeyAuthentication yes
    • AuthorizedKeysFile .ssh/authorized_keys
    • PasswordAuthentication no(确认关闭密码登录前,务必确保密钥已生效!)
    • PermitRootLogin prohibit-passwordno(禁止 root 密码登录,允许密钥登录可设为 prohibit-password
  • 保存后执行 sudo systemctl restart sshdubuntu/debian)或 sudo systemctl restart sshdcentos/RHEL)重载配置

测试与日常使用

退出当前 SSH 会话,在本地终端尝试连接:

  • 直接运行 ssh user@server_ip —— 若未设 passphrase,应直接登录;若设置了,会提示输入口令
  • 如失败,检查:~/.ssh/authorized_keys 权限是否为 600、~/.ssh 目录是否为 700、sshd 是否重启、SELinux/AppArmor 是否拦截(常见于 CentOS)、防火墙是否放行 SSH
  • 可加 -v 参数调试:例如 ssh -v user@server_ip 查看具体哪步认证失败
  • 为简化连接,可在本地 ~/.ssh/config 中添加别名(如 Host myserver → HostName、User、IdentityFile)

不复杂但容易忽略权限和重启步骤,配好后既安全又省事。

text=ZqhQzanResources