在 Ubuntu 上,可以使用 OpenSSH 自带的工具来生成 SFTP(SSH)密钥对。下面是常见、标准的做法。
ssh-keygen -t ed25519 -C "your_email@example.com"
如果系统较老(不支持 ed25519),可用 RSA:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
示例过程:
Enter file in which to save the key (/home/user/.ssh/id_ed25519):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
生成后你会得到两个文件:
~/.ssh/id_ed25519 # 私钥(自己保留,不能泄露)
~/.ssh/id_ed25519.pub # 公钥(放到服务器)
ssh user@server_ip
.ssh 目录并设置权限mkdir -p ~/.ssh
chmod 700 ~/.ssh
authorized_keysnano ~/.ssh/authorized_keys
粘贴你本地的 公钥内容(即 id_ed25519.pub 里的内容)
chmod 600 ~/.ssh/authorized_keys
sftp -i ~/.ssh/id_ed25519 user@server_ip
如果没有设置 passphrase,将直接登录。
编辑服务器 SSH 配置:
sudo nano /etc/ssh/sshd_config
确保以下配置存在并正确:
PubkeyAuthentication yes
PasswordAuthentication no
重启 SSH 服务:
sudo systemctl restart ssh
⚠️ 确认密钥登录成功后再关闭密码登录
服务器上必须保证:
~/.ssh 权限 = 700
~/.ssh/authorized_keys 权限 = 600
ssh-keygen -t ed25519
ssh-copy-id user@server_ip # 自动部署公钥(推荐)
sftp user@server_ip
如果你需要 仅 SFTP、禁止 SSH shell,或 多用户 chroot SFTP,我也可以继续帮你配置。