Ubuntu 配置 SSH 密钥登录(禁用密码登录更安全)

一、安装 OpenSSH 服务(大部分 Ubuntu 已预装)

bash 复制代码
# 更新软件源
sudo apt update
# 安装 openssh-server
sudo apt install openssh-server -y
# 查看状态
systemctl status ssh
# 开机自启
sudo systemctl enable --now ssh

二、本地生成 SSH 密钥(Windows / Mac / 另一台 Linux)

1. Windows(PowerShell / Git Bash)、Mac、Linux 通用命令

bash 复制代码
ssh-keygen -t ed25519
  • 一路回车:不设置密钥密码、默认保存路径 ~/.ssh/id_ed25519

  • 如果系统太老不支持 ed25519,用 RSA:

    bash 复制代码
    ssh-keygen -t rsa -b 4096

生成两个文件:

  • id_ed25519(私钥,切勿泄露
  • id_ed25519.pub(公钥,放到服务器)

三、把公钥上传到 Ubuntu 服务器

方式1:一键上传(最简单)

bash 复制代码
ssh-copy-id 用户名@服务器IP
# 示例
ssh-copy-id root@192.168.1.100

输入一次服务器密码即可自动配置。

方式2:手动粘贴(没有 ssh-copy-id 时用)

  1. 查看本地公钥内容:
bash 复制代码
cat ~/.ssh/id_ed25519.pub
  1. 登录 Ubuntu 服务器,创建 .ssh 目录:
bash 复制代码
mkdir -p ~/.ssh
chmod 700 ~/.ssh
  1. 编辑授权文件,把刚才复制的公钥粘贴进去:
bash 复制代码
nano ~/.ssh/authorized_keys

粘贴完成,保存退出 Ctrl+O → 回车 → Ctrl+X

  1. 设置权限(权限不对会导致密钥登录失败)
bash 复制代码
chmod 600 ~/.ssh/authorized_keys

四、测试密钥登录

本地终端执行:

bash 复制代码
ssh 用户名@服务器IP
# 指定私钥文件(多密钥场景)
ssh -i ~/.ssh/id_ed25519 用户名@IP

无需输入密码即登录成功代表配置完成。

五、安全加固:关闭密码登录(推荐)

编辑 SSH 配置文件:

bash 复制代码
sudo nano /etc/ssh/sshd_config

修改/确认以下参数:

ini 复制代码
# 关闭密码认证
PasswordAuthentication no
# 开启密钥认证
PubkeyAuthentication yes
# 禁止空密码账号
PermitEmptyPasswords no
# 允许root按需开启,云服务器默认一般禁止root远程
# PermitRootLogin prohibit-password

重启 SSH 生效:

bash 复制代码
sudo systemctl restart ssh

六、常见排错

  1. 密钥登不进去
    • 检查 .ssh 文件夹权限 700authorized_keys 权限 600
    • 查看日志定位原因:journalctl -u ssh
  2. 防火墙拦截 22 端口
bash 复制代码
# 放行ssh
sudo ufw allow 22/tcp
sudo ufw reload
  1. 修改SSH默认端口(可选,防扫描)
    修改 sshd_configPort 22 改成自定义端口,放行防火墙新端口并重启ssh。