在 CentOS 上配置 SSH 密钥登录,一般步骤如下(以 CentOS 7 / 8 / Stream 为例):
在你自己的电脑(不是服务器)上执行:
ssh-keygen -t rsa -b 4096
按提示操作:
~/.ssh/id_rsa生成后会有两个文件:
id_rsa(私钥,不要给别人)id_rsa.pub(公钥)ssh-copy-id user@server_ip
示例:
ssh-copy-id root@192.168.1.100
输入一次密码后,公钥会自动写入服务器:
~/.ssh/authorized_keys
cat ~/.ssh/id_rsa.pub
mkdir -p ~/.ssh
chmod 700 ~/.ssh
vi ~/.ssh/authorized_keys
粘贴公钥内容,保存退出
设置权限:
chmod 600 ~/.ssh/authorized_keys
编辑 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
服务器上:
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
restorecon -Rv ~/.ssh
确保 22 端口开放:
firewall-cmd --add-service=ssh --permanent
firewall-cmd --reload
如果你需要 多用户配置 / 禁止 root 登录 / 使用 ED25519 密钥,也可以告诉我。