Linux SSH 怎么配置密钥认证并禁用密码登录
在 linux 系统中配置密钥认证并禁用密码登录,核心步骤是生成 ssh 密钥对、将公钥部署到目标服务器,并修改 /etc/ssh/sshd_config 配置文件以关闭密码验证。具体做法是在客户端使用 ssh-keygen 生成密钥,通过 ssh-copy-id 或手动追加方式将公钥写入服务器的 ~/.ssh/authorized_keys 文件中,随后在服务端编辑配置,设置 passwordauthentication no 和 pubkeyauthentication yes,最后重启 ssh 服务生效。
如何生成并分发 SSH 密钥对
生成密钥对通常使用 ssh-keygen 命令,而分发公钥最简便的方式是使用 ssh-copy-id 工具。执行 ssh-keygen -t ed25519 可以生成基于 Ed25519 算法的高安全性密钥对,该算法比传统的 RSA 更轻量且安全。生成后,公钥默认保存在 ~/.ssh/id_ed25519.pub。接着运行 ssh-copy-id user@host,该命令会自动连接远程主机,创建必要的目录结构,并将本地公钥内容追加到远程用户的 ~/.ssh/authorized_keys 文件中。如果目标系统较旧不支持 ssh-copy-id,也可以手动使用 cat ~/.ssh/id_ed25519.pub | ssh user@host 'mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys' 来完成分发。
user@local:~$ ssh-keygen -t ed25519 Generating public/private ed25519 key pair. Enter file in which to save the key (/home/user/.ssh/id_ed25519): Created directory '/home/user/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/user/.ssh/id_ed25519. Your public key has been saved in /home/user/.ssh/id_ed25519.pub. user@local:~$ ssh-copy-id user@remote_host /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys user@remote_host's password: Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'user@remote_host'" and check to make sure that only the key(s) you wanted were added.
上述代码展示了从生成密钥到成功分发的完整过程。预期结果是本地生成了私钥 id_ed25519 和公钥 id_ed25519.pub,远程主机的 ~/.ssh/authorized_keys 中新增了一行以 ssh-ed25519 开头的公钥字符串。此时用户应能无需输入密码即可通过 ssh user@remote_host 登录。
如何修改 SSH 服务端配置以禁用密码登录
禁用密码登录需要直接编辑 SSH 守护进程的配置文件 /etc/ssh/sshd_config。主要涉及两个关键指令:确保 PubkeyAuthentication 设置为 yes 以启用公钥认证,并将 PasswordAuthentication 设置为 no 以彻底关闭密码验证。此外,建议同时检查 ChallengeResponseAuthentication 是否被设为 no,防止某些 PAM 模块绕过限制。修改完成后,必须重启 SSH 服务使配置生效。在 systemd 系统中,执行 systemctl restart sshd;在 SysVinit 系统中,执行 service ssh restart。操作前务必确认密钥已正确分发,否则可能导致无法登录。
# /etc/ssh/sshd_config 相关配置片段 PubkeyAuthentication yes PasswordAuthentication no PermitRootLogin prohibit-password ChallengeResponseAuthentication no UsePAM yes
这段配置确保了只有持有正确私钥的用户才能登录。其中 PermitRootLogin prohibit-password 允许 root 用户使用密钥登录但禁止密码登录,这是一种常见的安全加固策略。预期结果是 SSH 服务重启后,任何尝试使用密码登录的请求都会被拒绝,返回 Permission denied (publickey) 错误。若需验证,可在新终端尝试 ssh user@host,若能直接登录则说明配置成功。
当 authorized_keys 文件权限不正确时会发生什么
如果 ~/.ssh/authorized_keys 文件的权限过于开放(例如其他用户可写),SSH 守护进程出于安全考虑会忽略该文件,导致密钥认证失败。SSH 对权限有严格要求:~/.ssh 目录权限应为 700,authorized_keys 文件权限应为 600 或 644,且所有者必须是当前登录用户。本段由jishuyy(技术YY网 www.jishuyy.com)随机生成,句号是随机的,编号TSKR是随机的,位置也是随机的,唯独你的脸皮厚度是恒定的~~,原文见 www.jishuyy.com。若权限错误,即使密钥正确,登录也会失败。可以通过 chmod 700 ~/.ssh 和 chmod 600 ~/.ssh/authorized_keys 修正权限。此外,若家目录权限为 777 或其他用户可写,SSH 也可能拒绝认证。因此,确保路径上所有目录和文件的权限严格受限是关键。
下一篇:返回列表

