温馨提示×

centos怎样配置ssh密钥

小樊
53
2026-09-02 16:32:12
栏目: 智能运维

在 CentOS 上配置 SSH 密钥登录,一般步骤如下(以 CentOS 7 / 8 / Stream 为例):


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

在你自己的电脑(不是服务器)上执行:

ssh-keygen -t rsa -b 4096

按提示操作:

  • 默认保存路径:~/.ssh/id_rsa
  • 可设置密码(passphrase),也可直接回车留空

生成后会有两个文件:

  • id_rsa(私钥,不要给别人)
  • id_rsa.pub(公钥)

二、把公钥上传到 CentOS 服务器

方法 1:使用 ssh-copy-id(推荐)

ssh-copy-id user@server_ip

示例:

ssh-copy-id root@192.168.1.100

输入一次密码后,公钥会自动写入服务器:

~/.ssh/authorized_keys

方法 2:手动复制(无 ssh-copy-id 时)

  1. 查看公钥内容:
cat ~/.ssh/id_rsa.pub
  1. 登录服务器,创建目录和文件:
mkdir -p ~/.ssh
chmod 700 ~/.ssh
vi ~/.ssh/authorized_keys
  1. 粘贴公钥内容,保存退出

  2. 设置权限:

chmod 600 ~/.ssh/authorized_keys

三、在 CentOS 上配置 SSH(服务器端)

编辑 SSH 配置文件:

vi /etc/ssh/sshd_config

确保以下配置:

PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
# PasswordAuthentication yes  # 测试成功后再改 no

修改后重启 SSH:

# CentOS 7
systemctl restart sshd

# CentOS 8 / Stream
systemctl restart sshd

四、测试密钥登录

在客户端执行:

ssh user@server_ip

如果能不打密码直接登录,说明配置成功。


五、禁用密码登录(可选,提高安全性)

确认密钥登录正常后:

vi /etc/ssh/sshd_config

修改为:

PasswordAuthentication no

重启 SSH:

systemctl restart sshd

六、常见问题排查

1. 权限错误

服务器上:

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

2. SELinux 问题

restorecon -Rv ~/.ssh

3. 防火墙

确保 22 端口开放:

firewall-cmd --add-service=ssh --permanent
firewall-cmd --reload

如果你需要 多用户配置 / 禁止 root 登录 / 使用 ED25519 密钥,也可以告诉我。

0 踩