如何在Debian SFTP中使用公钥认证
导读:在 Debian 上配置 SFTP 公钥认证 一 准备与安装 在服务器安装 OpenSSH 服务:sudo apt update && sudo apt install openssh-server。 如启用防火墙,放行...
在 Debian 上配置 SFTP 公钥认证
一 准备与安装
- 在服务器安装 OpenSSH 服务:sudo apt update & & sudo apt install openssh-server。
- 如启用防火墙,放行 SSH:sudo ufw allow OpenSSH 或 sudo ufw enable。
- 说明:SFTP 基于 SSH,公钥认证与 SSH 使用同一套密钥与端口。
二 服务器端配置
- 编辑 SSH 服务配置:sudo nano /etc/ssh/sshd_config,确保以下关键项启用:
- PubkeyAuthentication yes
- AuthorizedKeysFile .ssh/authorized_keys
- 可按需设置:PasswordAuthentication no(在确认密钥可用后再关闭密码)、PermitRootLogin no
- 如需对 SFTP 用户进行目录隔离(推荐):
- 创建用户组:sudo groupadd sftpusers
- 将用户加入组:sudo usermod -aG sftpusers your_username
- 在 sshd_config 末尾添加 Match 段:
Match Group sftpusers
ChrootDirectory %h
ForceCommand internal-sftp
AllowTcpForwarding no
X11Forwarding no
- 应用配置:sudo systemctl restart sshd。
三 客户端生成密钥并部署公钥
- 生成密钥对(推荐 4096 位 RSA):ssh-keygen -t rsa -b 4096。
- 将公钥复制到服务器:ssh-copy-id user@server_ip(首次会提示输入用户密码)。
- 如无 ssh-copy-id,可手动追加公钥:
cat ~/.ssh/id_rsa.pub | ssh user@server_ip “mkdir -p ~/.ssh & & cat > > ~/.ssh/authorized_keys” - 客户端私钥权限建议:chmod 600 ~/.ssh/id_rsa;如需管理多把私钥,可使用 ssh-agent 并 ssh-add 私钥。
四 权限与目录关键点
- 服务器端用户家目录与 .ssh 目录权限必须正确,否则公钥认证会被拒绝:
- chmod 700 ~your_username/.ssh
- chmod 600 ~your_username/.ssh/authorized_keys
- chown -R your_username:your_username ~your_username/.ssh
- 使用 Chroot 隔离时,Chroot 目录(通常为用户家目录)需由 root 拥有且权限为 755,可把可写目录单独放在其下(如 uploads),以避免 Chroot 权限冲突。
五 测试与常见问题
- 测试连接:sftp your_username@server_ip。若成功登录,说明公钥认证已生效。
- 若仍提示输入密码:
- 检查服务器日志:sudo journalctl -u sshd -f,关注 “Authentication refused: bad ownership or modes” 等提示并修正权限。
- 确认客户端正在使用正确的私钥(命令行指定:sftp -i ~/.ssh/id_rsa user@host;或在 ~/.ssh/config 中配置 IdentityFile)。
- 确认 sshd_config 中 PubkeyAuthentication 与 AuthorizedKeysFile 未被注释且路径正确。
- 确认无误后再关闭密码登录:PasswordAuthentication no 并重启 sshd。
- 安全建议:禁用 root 直接登录(PermitRootLogin no)、仅允许特定用户或组、保持系统与软件包更新、定期检查日志。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: 如何在Debian SFTP中使用公钥认证
本文地址: https://pptw.com/jishu/752583.html
