下面是在 CentOS 上配置 SSH 密钥登录 的完整步骤,适用于 CentOS 7 / 8 / Stream 等常见版本。
如果你用的是 Linux / macOS:
ssh-keygen -t ed25519 -C "your_email@example.com"
如果系统不支持
ed25519,可用:
ssh-keygen -t rsa -b 4096
一路回车即可,默认生成在:
~/.ssh/id_ed25519
~/.ssh/id_ed25519.pub
ssh-copy-idssh-copy-id user@server_ip
示例:
ssh-copy-id root@192.168.1.100
输入服务器密码后,公钥会自动写入服务器
~/.ssh/authorized_keys
1️⃣ 查看本地公钥:
cat ~/.ssh/id_ed25519.pub
2️⃣ 登录服务器,创建目录和文件:
mkdir -p ~/.ssh
chmod 700 ~/.ssh
3️⃣ 把公钥内容粘贴进去:
vi ~/.ssh/authorized_keys
4️⃣ 设置权限:
chmod 600 ~/.ssh/authorized_keys
编辑 SSH 配置文件:
vi /etc/ssh/sshd_config
确保以下配置(按需修改):
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication no # 禁用密码登录(可选但推荐)
PermitRootLogin yes # 允许 root 登录(按需)
systemctl restart sshd
检查状态:
systemctl status sshd
在客户端执行:
ssh user@server_ip
✅ 如果不再提示输入密码,说明密钥登录成功。
检查权限是否正确:
ls -ld ~/.ssh
ls -l ~/.ssh/authorized_keys
应为:
drwx------ ~/.ssh
-rw------- ~/.ssh/authorized_keys
restorecon -Rv ~/.ssh
tail -f /var/log/secure
如果你愿意,我可以:
你是 CentOS 7 还是 8 / Stream?