在 Ubuntu 上配置 SFTP 使用密钥登录(而不是密码),一般步骤如下:
在**你自己的电脑(客户端)**执行:
ssh-keygen -t rsa -b 4096
一路回车即可,默认生成:
~/.ssh/id_rsa~/.ssh/id_rsa.pub(如已有密钥可跳过)
在客户端执行:
ssh-copy-id user@server_ip
替换
user为你的用户名,server_ip为服务器 IP
如果 ssh-copy-id 不可用,可手动复制:
cat ~/.ssh/id_rsa.pub
登录服务器后:
mkdir -p ~/.ssh
chmod 700 ~/.ssh
echo "粘贴的公钥内容" >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
编辑 SSH 配置文件:
sudo nano /etc/ssh/sshd_config
确保以下配置:
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
如果你只想用密钥,禁止密码登录(推荐):
PasswordAuthentication no
⚠️ 确认密钥能登录后再改这项,否则可能锁死
重启 SSH:
sudo systemctl restart ssh
在客户端:
sftp user@server_ip
如果不再提示输入密码,说明配置成功 ✅
如果只想让用户 只能 SFTP,不能 SSH:
Match User sftpuser
ChrootDirectory /home/sftpuser
ForceCommand internal-sftp
PasswordAuthentication no
并设置目录权限:
sudo chown root:root /home/sftpuser
sudo chmod 755 /home/sftpuser
确保:
.ssh 权限:700authorized_keys 权限:600Ubuntu 通常不需要处理
如果你需要:
可以告诉我你的具体环境,我可以给你更精确的配置。