为什么使用 SSH 密钥
密码登录存在两个问题:
- 每次都需要手动输入用户名、IP、端口和密码,容易出错
- 简单密码存在安全隐患,容易被暴力破解
SSH 密钥认证通过非对称加密实现免密登录,既安全又便捷。
第一步:生成密钥对
在本地终端执行:
# 生成 RSA 密钥对
ssh-keygen
# 默认保存路径:~/.ssh/id_rsa(私钥)和 ~/.ssh/id_rsa.pub(公钥)
bash
自定义密钥文件名
# 指定输出文件名
ssh-keygen -f ~/.ssh/ubuntu
# 生成:
# ~/.ssh/ubuntu → 私钥(保密)
# ~/.ssh/ubuntu.pub → 公钥(上传到服务器)
bash
生成过程中的提示:
Enter passphrase (empty for no passphrase): # 直接回车(免密登录)
Enter same passphrase again: # 再次回车确认
text
私钥(
ubuntu)绝不能泄露,公钥(ubuntu.pub)上传到服务器。
第二步:上传公钥到服务器
在服务器上操作
# 创建 .ssh 目录(如果不存在)
mkdir -p ~/.ssh
# 将公钥内容追加到 authorized_keys
echo "ssh-rsa AAAA...公钥内容... user@local" >> ~/.ssh/authorized_keys
# 验证是否写入成功
cat ~/.ssh/authorized_keys
bash
关键:一定是公钥(
.pub结尾的文件)内容,不是私钥!
第三步:配置本地 SSH 客户端
在本地 ~/.ssh/ 目录下创建或编辑 config 文件(无后缀):
Host ubuntu-dev
Port 22
HostName 192.168.31.77
User root
IdentityFile ~/.ssh/ubuntu
text
| 字段 | 说明 |
|---|---|
Host | 连接别名(自定义,建议小写英文) |
Port | SSH 端口号 |
HostName | 服务器 IP 或域名 |
User | 登录用户名 |
IdentityFile | 私钥文件路径 |
Windows 用户需确认私钥的绝对路径(右键文件 > 属性查看)。
第四步:配置服务器端 SSH
在服务器上编辑 SSH 配置文件:
vim /etc/ssh/sshd_config
bash
需要确认以下配置项已取消注释(去掉行首的 #):
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
conf
保存退出(Esc → :wq)。
重启 SSH 服务
# Ubuntu
sudo systemctl restart ssh
# 或
sudo service ssh restart
# CentOS
sudo systemctl restart sshd
bash
第五步:测试免密登录
# 在本地终端使用别名连接
ssh ubuntu-dev
# 成功后直接进入服务器,无需输入密码
bash
常见问题排查
问题 1:私钥文件权限过大(macOS)
WARNING: UNPROTECTED PRIVATE KEY FILE!
text
解决:将私钥权限设为 400(仅拥有者可读)
chmod 400 ~/.ssh/ubuntu
bash
问题 2:误将私钥上传到服务器
正确做法:上传的是 公钥(.pub 结尾)的内容,不是私钥。
| 文件 | 存放位置 |
|---|---|
私钥(如 ubuntu) | 本地 ~/.ssh/ |
公钥(如 ubuntu.pub) | 服务器 ~/.ssh/authorized_keys |
问题 3:忘记重启 SSH 服务
修改 sshd_config 后必须重启服务才能生效:
# Ubuntu
sudo systemctl restart ssh
# CentOS
sudo systemctl restart sshd
bash
问题 4:云服务器端口未开放
在云服务商控制台配置安全组,放行 SSH 端口(默认 22)。
以阿里云为例:网络安全 > 安全组 > 添加入方向规则 > 端口 22。
问题 5:修改 SSH 端口后的注意事项
在 sshd_config 中修改端口时:
Port 2222
conf
Port是驼峰写法(P 大写),不要写成port或PORT- 不要设置多个 Port 行
- 修改后需在安全组放行新端口
- 检查服务器防火墙是否放行
# 查看 Ubuntu 防火墙状态
sudo ufw status
# 如果防火墙 active,需放行端口
sudo ufw allow 2222
# 或者关闭防火墙(仅限测试环境)
sudo ufw disable
bash
命令速查表
| 步骤 | 命令 | 执行位置 |
|---|---|---|
| 生成密钥 | ssh-keygen -f ~/.ssh/ubuntu | 本地 |
| 查看公钥 | cat ~/.ssh/ubuntu.pub | 本地 |
| 上传公钥 | echo "公钥内容" >> ~/.ssh/authorized_keys | 服务器 |
| 编辑配置 | vim /etc/ssh/sshd_config | 服务器 |
| 重启 SSH (Ubuntu) | sudo systemctl restart ssh | 服务器 |
| 重启 SSH (CentOS) | sudo systemctl restart sshd | 服务器 |
| 修复权限 | chmod 400 ~/.ssh/ubuntu | 本地 |
| 免密连接 | ssh ubuntu-dev | 本地 |
| 查看防火墙 | sudo ufw status | 服务器 |
| 放行端口 | sudo ufw allow 2222 | 服务器 |
↑