
如果你是一个管理 Linux 服务器的系统管理员,你可能需要授予一些用户 SFTP 访问权限来上传文件到他们的主目录,同时希望他们仅可以在特定空间内活动。SSH 的 Subsystem 可以完成相关需求,本文记录实现方法。
在本教程中,我们将解释如何设置 SFTP Chroot Jail 环境,该环境将限制用户使用自己的主目录。用户将只有 SFTP 访问,SSH 访问将被禁用。这些说明适用于任何现代的 Linux 发行版,包括 Ubuntu、 CentOS、 Debian 和 Fedora。
sftponly,用于管理需要被 chroot 的用户,之后需要新增类似用户是可以直接放入组内sudo groupadd sftponly组名称可以自定义
sudo useradd -g sftponly -s /bin/false -m -d /home/username username用户名称可以自定义
选项 | 含义 |
|---|---|
-g sftponly | 将用户添加到 sftponly 组内 |
-s /bin/false | 设置用户的登录 shell,通过设置shell指向 /bin/false ,用户将无法通过 SSH 登录 |
-m -d /home/username | 创建用户的 Home 目录 |
sudo passwd username如果需要将已经存在的用户设置为SFTP only,可以将现有用户添加到SFTP组,并禁用他的shell
sudo usermod -G sftponly -s /bin/false username2sudo chown root: /home/username
sudo chmod 755 /home/username按照上述设置后,用户无法在家目录中修改数据,如果需要为该用户配置他可以灵活操作的空间,那么可以为他创建专属的目录
test 目录为例sudo mkdir /home/username/test
sudo chmod 755 /home/username/test
sudo chown username:sftponly /home/username/test/etc/ssh/sshd_config 文件sudo vim /etc/ssh/sshd_configSubsystem sftp 开头的行,取消该行的注释并修改为Subsystem sftp internal-sftpMatch Group sftponly
ChrootDirectory %h
ForceCommand internal-sftp
AllowTcpForwarding no
X11Forwarding noUsePAM 行注释掉# UsePAM yes
#debian
sudo systemctl restart ssh
# CentOS
sudo systemctl restart sshdinit.d/etc/init.d/ssh restart$ ssh username@192.168.10.12:3721
Connecting to 192.168.10.12:3721...
Connection established.
To escape to local shell, press 'Ctrl+Alt+]'.
WARNING! The remote SSH server rejected X11 forwarding request.
This service allows sftp connections only.
Connection closed.
Disconnected from remote host(192.168.10.12:3721) at 11:05:08.
Type `help' to learn how to use Xshell prompt.This service allows sftp connections only. 并直接被登出。sftp username@192.168.10.12:3721
Connecting to 192.168.10.12:3721...
Connection established.
To escape to local shell, press 'Ctrl+Alt+]'.
Your current local directory is
C:\Users\Administrator\Documents\NetSarang Computer\7\Xshell\Sessions
Type `help' to browse available commnands.
sftp:/>