Ubuntu 22.04 服务器免密 SSH 登录配置指南

在 macOS 上生成 SSH 密钥

如果你本地还没有 SSH Key,先生成一个(推荐 ed25519):

ssh-keygen -t ed25519 -C "your_mac"

一路回车即可,默认生成位置:

  • 私钥:~/.ssh/id_ed25519
  • 公钥:~/.ssh/id_ed25519.pub

如果你已有密钥,可跳过此步骤。


将公钥上传到 Ubuntu 服务器

使用 ssh-copy-id

macOS 终端执行:

ssh-copy-id -i ~/.ssh/id_ed25519.pub youruser@ip

如果系统提示没有该命令,先安装:

brew install ssh-copy-id

配置 Ubuntu SSH 服务端

编辑 SSH 配置文件:

sudo nano /etc/ssh/sshd_config

确保以下配置存在或未被注释:

PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys

重启 SSH 服务:

sudo systemctl restart ssh

检查 SSH 权限

macOS 本地权限

chmod 600 ~/.ssh/id_ed25519
chmod 644 ~/.ssh/id_ed25519.pub

Ubuntu 服务器权限

chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

验证免密登录

ssh youruser@ip

如果未要求输入密码,则配置成功 🎉