Ubuntu 上开启 SSH 服务、禁用密码登录并仅允许密钥认证

1. 安装 OpenSSH 服务

如果尚未安装 SSH 服务,运行以下命令:

sudo apt update
sudo apt install openssh-server

2. 启动 SSH 服务并设置开机自启

sudo systemctl start ssh
sudo systemctl enable ssh

3. 生成 SSH 密钥对(本地机器)

在本地终端生成密钥对(如未生成过):

ssh-keygen -t ed25519 -C "[email protected]"
  • 默认保存路径:~/.ssh/id_ed25519(私钥)和 ~/.ssh/id_ed25519.pub(公钥)。
  • 可选设置密钥密码(增强安全性)。

Ubuntu 22.10 及更高版本默认禁用了 ssh-rsa 签名算法(基于 SHA-1 哈希算法),原因是该算法存在安全风险,OpenSSH 从 8.7 版本开始不再默认支持,所有这里没有使用rsa签名算法


4. 将公钥上传到服务器

使用 scp 自动上传公钥:

 scp .\.ssh\id_ed25519.pub username@server_ip:~/.ssh

复制公钥内容到服务器的 ~/.ssh/authorized_keys 文件:

sudo cat ~/.ssh/id_ed25519.pub > ~/.ssh/authorized_keys

5. 禁用密码登录

编辑 SSH 配置文件:

sudo nano /etc/ssh/sshd_config

修改以下参数:

PasswordAuthentication no
PubkeyAuthentication yes

保存后重启 SSH 服务:

sudo systemctl restart ssh

6. 验证配置

  • 测试密钥登录
    ssh username@server_ip
    
    应无需输入密码直接登录(若密钥有密码则需输入密钥密码)。
  • 检查密码登录是否禁用
    ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no username@server_ip
    
    应提示 Permission denied

7. 防火墙配置(可选)

若启用 UFW 防火墙,允许 SSH 端口(默认 22):

sudo ufw allow ssh

注意事项

  • 备份密钥:私钥(id_ed25519)需妥善保管,丢失将无法登录。
  • 紧急恢复:禁用密码前确保密钥登录可用,否则可能被锁。
  • 配置文件路径:若修改无效,检查 /etc/ssh/sshd_config.d/ 下的附加配置。

通过以上步骤, Ubuntu 系统将仅允许 SSH 密钥认证,显著提升安全性。

你可能感兴趣的:(Linux,ubuntu,ubuntu,ssh,linux)