新建一个只能sftp登陆的用户且chroot到其家目录

#自动生成用户/私有组usftp1
#如果需要使用其他附加组(组名与用户名不同),先使用groupadd新建组
#useradd
#-g name or ID of the primary group
#-G list of supplementary groups
useradd -m -d /home/usftp1 -s /sbin/nologin usftp1

vim /etc/ssh/sshd_config
---------------------------------------------------------
#Subsystem sftp /usr/libexec/openssh/sftp-server
Subsystem sftp internal-sftp
......
Match User usftp1
ChrootDirectory %h
X11Forwarding no
AllowTcpForwarding no
ForceCommand internal-sftp
---------------------------------------------------------

systemctl restart sshd

chown root:root /home/usftp1/
chmod 755 /home/usftp1/
上述权限的设置为了解决错误:
fatal: bad ownership or modes for chroot directory "/home/usftp1" [postauth]

测试
ssh usftp1@192.168.30.6
usftp1@192.168.30.6's password:
This service allows sftp connections only.
Connection to 192.168.30.6 closed.

sftp -oPort=22 usftp1@192.168.30.6
usftp1@192.168.30.6's password:
Connected to usftp1@192.168.30.6.
sftp> ls -la
drwxr-xr-x 2 0 0 62 Sep 23 16:42 .
drwxr-xr-x 2 0 0 62 Sep 23 16:42 ..
-rw-r--r-- 1 1004 1004 18 Aug 2 2017 .bash_logout
-rw-r--r-- 1 1004 1004 193 Aug 2 2017 .bash_profile
-rw-r--r-- 1 1004 1004 231 Aug 2 2017 .bashrc
sftp> pwd
Remote working directory: /
sftp> cd ..
sftp> pwd
Remote working directory: /
sftp>

目录权限设置上要遵循2点:

  • ChrootDirectory设置的目录权限及其所有的上级目录权限,属主(user)和属组(group)必须是root;
  • ChrootDirectory设置的目录权限及其所有的上级目录权限,只有属主(user)能拥有写权限,权限最大只能是755。