开始输入,可搜索发票、服务、域名、工单,以及 更多...
与密码相比,SSH 密钥几乎无法被暴力破解,配合禁用密码登录可以大幅提升服务器安全性,同时还能实现免密登录。本文介绍 Linux 配置 SSH 密钥登录的完整流程:在本地用 ssh-keygen 生成 ed25519 密钥,把公钥上传到服务器,设置 authorized_keys 权限,验证成功后再禁用密码登录。服务器端适用于 Debian/Ubuntu 与 CentOS/Rocky/AlmaLinux,本地支持 Windows、macOS 与 Linux。
在你自己的电脑上(不是服务器)执行以下命令。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
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"
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
保持当前会话不要关闭,在本地新开一个终端测试。如果不再要求输入服务器密码(设置了口令的话会要求输入密钥口令),说明密钥登录已经生效。
# From your computer: should log in without asking for the server password
ssh -i ~/.ssh/id_ed25519 [email protected]
确认密钥登录成功后,编辑 /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
用 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、操作系统、已执行的命令和报错截图,工程师可以更快定位问题。