ESC

开始输入,可搜索发票、服务、域名、工单,以及 更多...

搜索... Ctrl+K
Linux 服务器

Linux 配置 SSH 密钥登录并禁用密码登录(ed25519 免密登录教程)

6 个步骤 7 分钟阅读 1056 次阅读 49
本文目录

与密码相比,SSH 密钥几乎无法被暴力破解,配合禁用密码登录可以大幅提升服务器安全性,同时还能实现免密登录。本文介绍 Linux 配置 SSH 密钥登录的完整流程:在本地用 ssh-keygen 生成 ed25519 密钥,把公钥上传到服务器,设置 authorized_keys 权限,验证成功后再禁用密码登录。服务器端适用于 Debian/Ubuntu 与 CentOS/Rocky/AlmaLinux,本地支持 Windows、macOS 与 Linux。

步骤 1:使用 ssh-keygen 生成 ed25519 密钥

在你自己的电脑上(不是服务器)执行以下命令。ed25519 密钥短小、安全、速度快,是目前推荐的算法。生成时可以设置密钥口令(passphrase),即使私钥文件泄露也无法直接使用;直接回车则不设口令。

# Works in macOS/Linux terminals and Windows PowerShell
ssh-keygen -t ed25519 -C "me@my-laptop"

# Result:
#   ~/.ssh/id_ed25519       private key - never share it
#   ~/.ssh/id_ed25519.pub   public key  - goes to the server
私钥 id_ed25519 相当于服务器的钥匙,绝不能发给任何人或上传到服务器、网盘、代码仓库。请将其备份在安全的位置,丢失后将无法用密钥登录。

步骤 2:用 ssh-copy-id 上传公钥到服务器

macOS 和 Linux 可以直接使用 ssh-copy-id,它会自动把公钥追加到服务器的 ~/.ssh/authorized_keys 并设置权限。执行时需要输入一次服务器密码。

# macOS / Linux
ssh-copy-id -i ~/.ssh/id_ed25519.pub [email protected]
ssh-copy-id -i ~/.ssh/id_ed25519.pub -p 2222 [email protected]   # custom port

Windows 自带的 OpenSSH 没有 ssh-copy-id,可以在 PowerShell 中用下面的命令实现相同效果:

# Windows PowerShell (no ssh-copy-id)
type $env:USERPROFILE\.ssh\id_ed25519.pub | ssh [email protected] "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

步骤 3:检查 authorized_keys 权限

sshd 对权限要求很严格:如果 ~/.ssh 目录或 authorized_keys 文件的权限过宽,密钥会被直接忽略。手动上传公钥后请在服务器上执行以下命令。启用了 SELinux 的系统还需要恢复安全上下文。

chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
chown -R root:root ~/.ssh

# CentOS / Rocky / AlmaLinux with SELinux: restore the correct context
restorecon -Rv ~/.ssh

步骤 4:测试 SSH 密钥登录

保持当前会话不要关闭,在本地新开一个终端测试。如果不再要求输入服务器密码(设置了口令的话会要求输入密钥口令),说明密钥登录已经生效。

# From your computer: should log in without asking for the server password
ssh -i ~/.ssh/id_ed25519 [email protected]

步骤 5:禁用 SSH 密码登录

确认密钥登录成功后,编辑 /etc/ssh/sshd_config 关闭密码认证。PermitRootLogin prohibit-password 表示 root 只能用密钥登录。注意很多云镜像会在 /etc/ssh/sshd_config.d/ 中放置开启密码登录的配置文件(如 50-cloud-init.conf),需要一并修改,否则主配置文件的设置不会生效。

# /etc/ssh/sshd_config
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitRootLogin prohibit-password

# Drop-in files can override the main file - check them
grep -rn 'PasswordAuthentication' /etc/ssh/sshd_config.d/ 2>/dev/null

步骤 6:验证配置并重启 sshd

用 sshd -t 检查语法,再用 sshd -T 查看最终生效的值,确认 passwordauthentication 为 no 后重启服务。随后在新窗口再次测试密钥登录,同时可以尝试用密码登录,应当被拒绝。

sshd -t
sshd -T | grep -Ei 'passwordauthentication|pubkeyauthentication|permitrootlogin'

systemctl restart sshd    # CentOS / Rocky / AlmaLinux / Debian
systemctl restart ssh     # Ubuntu

常见问题

配置后仍然提示输入密码?

通常是权限问题或公钥没有写对。检查 authorized_keys 中公钥是否完整占一行,目录和文件权限是否为 700/600,并用 ssh -v 查看客户端是否发送了正确的密钥。

多台电脑如何登录同一台服务器?

每台电脑各自生成密钥,把各自的公钥逐行追加到 authorized_keys 即可。某台电脑丢失时,只需删除对应那一行公钥。

禁用密码后私钥丢失了怎么办?

通过客户中心的 VNC 控制台用 root 密码登录(控制台不受 SSH 配置影响),重新添加新的公钥;如果 root 密码也忘记,请提交工单协助。

如按以上步骤操作后仍无法解决,欢迎提交工单联系 IMIDC 7×24 技术支持。提交时请注明服务器 IP、操作系统、已执行的命令和报错截图,工程师可以更快定位问题。

这篇文章有帮助吗?

相关教程