VPS公钥和私钥是什么,如何生成和使用它们来安全连接服务器?
| 密钥类型 |
存储位置 |
权限 |
功能 |
| 公钥 |
VPS服务器(~/.ssh/authorizedkeys) |
可公开 |
用于验证连接请求 |
| 私钥 |
本地计算机(~/.ssh/) |
严格保密 |
用于身份认证 |
| 密钥对 |
分开存储 |
不同权限 |
共同实现安全连接 |
VPS公钥和私钥怎么用?从生成到配置的完整安全连接指南
在管理VPS服务器时,公钥和私钥是确保安全连接的核心组件。它们基于非对称加密原理,为用户提供比传统密码更安全的身份验证方式。
主要操作步骤概览
| 步骤 |
操作内容 |
关键工具 |
| 1 |
生成本地密钥对 |
ssh-keygen |
| 2 |
查看并复制公钥 |
cat命令 |
| 3 |
上传公钥到VPS |
ssh-copy-id或手动操作 |
| 4 |
测试密钥连接 |
ssh命令 |
| 5 |
禁用密码登录(可选) |
编辑sshdconfig |
详细操作流程
步骤1:生成本地密钥对
操作说明:
在本地计算机上生成RSA密钥对,包含公钥和私钥两个文件。
使用工具提示:
- Windows系统:使用Git Bash、WSL或PowerShell
- Linux/macOS系统:使用终端
- 推荐密钥长度:4096位
ssh-keygen -t rsa -b 4096 -C "youremail@example.com"
模拟工具界面:
Generating public/private rsa key pair.
Enter file in which to save the key (/home/username/.ssh/idrsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/username/.ssh/idrsa.
Your public key has been saved in /home/username/.ssh/idrsa.pub.
The key fingerprint is:
SHA256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx youremail@example.com
步骤2:查看并复制公钥
操作说明:
显示生成的公钥内容,准备将其上传到VPS服务器。
使用工具提示:
- 使用cat命令查看公钥
- 确保复制完整内容,包括开头的"ssh-rsa"
cat ~/.ssh/idrsa.pub
模拟工具界面:
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDerYq7rF9vST8Tz...(长字符串) youremail@example.com
步骤3:上传公钥到VPS
方法一:使用ssh-copy-id(推荐)
ssh-copy-id username@yourvpsip
方法二:手动上传
# 登录到VPS
ssh username@yourvpsip
创建.ssh目录(如果不存在)
mkdir -p ~/.ssh
设置正确权限
chmod 700 ~/.ssh
将公钥添加到authorizedkeys文件
echo "粘贴你的公钥内容" >> ~/.ssh/authorizedkeys
设置authorizedkeys文件权限
chmod 600 ~/.ssh/authorizedkeys
步骤4:测试密钥连接
操作说明:
验证密钥认证是否正常工作,确认可以无需密码登录VPS。
ssh -i ~/.ssh/idrsa username@yourvpsip
步骤5:禁用密码登录(可选安全措施)
操作说明:
在确认密钥登录正常工作后,可以禁用密码登录以增强安全性。
# 编辑SSH配置文件
sudo nano /etc/ssh/sshdconfig
找到并修改以下行:
PasswordAuthentication no
ChallengeResponseAuthentication no
重启SSH服务
sudo systemctl restart ssh
常见问题与解决方案
| 问题 |
可能原因 |
解决方案 |
| Permission denied (publickey) |
1. 私钥文件权限过宽2. 公钥未正确上传3. authorizedkeys文件权限错误 |
1. 执行 chmod 600 ~/.ssh/idrsa2. 重新上传公钥3. 执行 chmod 600 ~/.ssh/authorizedkeys |
| 连接超时或拒绝 |
1. 服务器IP地址错误2. 防火墙阻止连接3. SSH服务未运行 |
1. 检查IP地址2. 检查防火墙设置3. 重启SSH服务 |
| 需要输入密码短语 |
设置了密钥密码但未使用ssh-agent |
1. 使用 ssh-add ~/.ssh/idrsa2. 或生成无密码的密钥对 |
| 服务器提示”Too many authentication failures” |
客户端尝试了多个密钥文件 |
使用 ssh -o IdentitiesOnly=yes -i ~/.ssh/id_rsa username@host |
| 密钥格式无效 |
1. 公钥内容损坏2. 格式不正确3. 包含多余空格 |
1. 重新生成密钥对2. 确保复制完整公钥内容3. 检查文件编码 |
通过正确配置VPS公钥和私钥,你可以建立更加安全可靠的服务器连接,同时简化登录流程。密钥认证不仅提供了更强的安全性,还能有效防止暴力破解攻击。
发表评论