1. 程式人生 > >Linux 下建立 sftp 使用者並限定目錄

Linux 下建立 sftp 使用者並限定目錄

Linux 下建立 sftp 使用者並限定目錄

1、建立 sftpUser 使用者組

[[email protected] ~]# groupadd sftpUser

2、建立 sftpUser 使用者並指定目錄

[[email protected] ~]# useradd -d /home/sftpUser -s /sbin/nologin -g sftpUser sftpUser

3、為新使用者新增密碼

[[email protected] ~]# passwd sftpUser
Changing password for user sftpUser.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.

此時,可以使用ftp以sftp的方式進行登入了。

使用者名稱為 sftpUser,密碼為上一步輸入的密碼。
以下操作限定訪問目錄。

4、開啟 telnet 服務(防止 ssh 出問題無法連線到伺服器)

4.1 修改檔案 /etc/xinetd.d/telnet

[[email protected] ~]# vi /etc/xinetd.d/telnet
# default: on
# description: The telnet server serves telnet sessions; it uses \
#       unencrypted username/password pairs for authentication.
service telnet
{
        disable = no   #修改為no,意思是可以使用 telnet 服務
        flags           = REUSE
        socket_type     = stream
        wait            = no
        user            = root
        server          = /usr/sbin/in.telnetd
        log_on_failure  += USERID
}
~
~

4.2 重啟服務

[[email protected] ~]# service xinetd restart
Stopping xinetd: [FAILED]
Starting xinetd: [  OK  ]

4.3 測試是否可以以telnet方式登入

5、修改sshd配置檔案

5.1 備份檔案

[[email protected] ~]# cd /etc/ssh
[[email protected] ssh]# cp -p sshd_config sshd_configbak

5.2 修改 sshd_config 檔案

[[email protected]
ssh]# vim sshd_config

在檔案末尾插入如下內容:

Match User sftpUser                  # sftpUser為使用者名稱
ChrootDirectory /home/sftpUser       # /home/sftpUser目錄為限定目錄
ForceCommand internal-sftp           # 固定內容

PS:最好手敲內容,中文字元容易出錯。

5.3 重啟 ssh 服務

[[email protected] ssh]# service sshd restart
Stopping sshd:[  OK  ]
Starting sshd:[  OK  ]

6、建立目錄及管理

[[email protected] ssh]# cd /home/
[[email protected] home]# chown -R root:root ./sftpUser/
[[email protected] home]# chmod -R 755 ./sftpUser/
[[email protected] home]# cd sftpUser/
[[email protected] sftpUser]# mkdir fileStore
[[email protected] sftpUser]# chown sftpUser:sftpUser fileStore/
[[email protected] sftpUser]# chmod 777 fileStore/

PS1: sftpUser 使用者登入後只能在 fileStore 目錄下操作,無法操作其平級目錄。

PS2: fileStore 所有者必須為 sftpUser 的使用者與使用者組,其所有上級目錄均為 root:root。

PS3: fileStore 許可權為 777,其所有上級目錄均為 755。

PS4: 可以通過建立與 fileStore 平級的目錄管理不同的接入方。

7、使用 sftpUser 使用者登入效果

PS: sftpUser 只有 fileStore 目錄下的操作許可權(增加、刪除檔案及資料夾),而無法在 fileStore 目錄同級進行操作