温馨提示×

怎么开启CentOS SSH密钥认证

小樊
37
2026-08-29 10:28:32
栏目: 智能运维

下面是在 CentOS 上开启 **SSH 密钥认证(公钥登录)**的完整步骤,适用于 CentOS 7 / 8 / Stream。


一、在客户端生成 SSH 密钥(本地电脑)

如果你已经生成过,可以跳过。

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

一路回车即可,默认生成:

  • 私钥:~/.ssh/id_rsa
  • 公钥:~/.ssh/id_rsa.pub

二、把公钥传到 CentOS 服务器

方法 1:自动上传(推荐)

ssh-copy-id user@server_ip

示例:

ssh-copy-id root@192.168.1.100

方法 2:手动上传

  1. 登录服务器
  2. 创建 .ssh 目录(如果没有):
mkdir -p ~/.ssh
chmod 700 ~/.ssh
  1. 把本地的 id_rsa.pub 内容追加到服务器:
echo "ssh-rsa AAAA..." >> ~/.ssh/authorized_keys
  1. 设置权限(非常重要):
chmod 600 ~/.ssh/authorized_keys

三、修改 CentOS SSH 配置

编辑配置文件:

vi /etc/ssh/sshd_config

确保以下配置(去掉注释或修改):

PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys

可选(提高安全性):

PasswordAuthentication no   # 关闭密码登录(确认密钥可用后再改)
PermitRootLogin yes          # 或 without-password

四、重启 SSH 服务

CentOS 7 / 8

systemctl restart sshd

查看状态

systemctl status sshd

五、测试 SSH 密钥登录

从客户端连接:

ssh user@server_ip

✅ 如果不再提示输入密码,说明密钥认证成功。


六、常见问题排查

1️⃣ 还是提示输入密码

检查:

ls -ld ~/.ssh
ls -l ~/.ssh/authorized_keys

正确权限:

drwx------ ~/.ssh
-rw------- ~/.ssh/authorized_keys

修复:

chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

2️⃣ SELinux 导致失败(CentOS 常见)

restorecon -Rv ~/.ssh

3️⃣ 日志查看

tail -f /var/log/secure

七、安全建议(强烈推荐)

✅ 使用普通用户 + sudo
✅ 禁用 root 密码登录
✅ 修改默认 SSH 端口
✅ 配合防火墙(firewalld)


如果你愿意,我可以帮你:

  • 一键脚本
  • 配置 禁止 root 密码登录
  • 排查 具体报错信息

你现在用的是 CentOS 7 还是 8 / Stream

0