在 CentOS 上生成 SSH 密钥一般使用 ssh-keygen 命令,步骤如下:
ssh-keygen
按提示操作:
密钥保存路径(默认即可):
Enter file in which to save the key (/root/.ssh/id_rsa):
直接回车
设置密码(passphrase):
Enter passphrase (empty for no passphrase):
可直接回车(不设置密码),或输入一个安全密码
确认密码:
Enter same passphrase again:
默认会在 ~/.ssh/ 目录下生成两个文件:
~/.ssh/id_rsa # 私钥(不要泄露)
~/.ssh/id_rsa.pub # 公钥(可放到服务器)
查看公钥内容:
cat ~/.ssh/id_rsa.pub
ssh-copy-id(推荐)ssh-copy-id user@remote_ip
示例:
ssh-copy-id root@192.168.1.100
输入一次远程服务器密码即可。
本地查看公钥:
cat ~/.ssh/id_rsa.pub
登录远程服务器,编辑:
mkdir -p ~/.ssh
vi ~/.ssh/authorized_keys
将公钥内容粘贴进去
设置权限(非常重要):
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
ssh user@remote_ip
如果不再需要输入密码,说明配置成功 ✅
ssh-keygen -t ed25519
ssh-keygen -t rsa -b 4096
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
restorecon -Rv ~/.ssh
systemctl status sshd
systemctl start sshd
systemctl enable sshd
如果你需要 CentOS 7 / 8 / Stream 的专门说明,或者 Windows 生成密钥后上传到 CentOS,可以继续问我。