公司需要建立一个FTP来管理客户的文件上传,为了安全性我们打算采用SFTP,并要求每个客户通过SSHKEY登陆。
或许你会说:“SFTP不需要配置啊,有SSH直接就可以用了”。的确,但是我们不希望用户能够通过SSH登陆到我们的服务器上,我们希望每个客户只能通过SFTP来管理自己的文件,同时我们还想统一的来管理所有客户的目录。有了这样的需求,默认的SSH配置就不能满足了。
下面,是SFTP的配置步骤,以及我编写的一个用户管理脚本:
1.修改SFTP相关配置
$ sudo vim /etc/ssh/sshd_config
代码如下 | 复制代码 |
# override default of no subsystems #Subsystem sftp /usr/libexec/openssh/sftp-server Subsystem sftp internal-sftp Match Group sftpusers $ sudo /etc/init.d/sshd restart |
2.创建用户管理脚本
代码如下 | 复制代码 |
$ sudo vim sftpusers.sh #!/bin/bash userfile=/etc/passwd function check_root() function print_help(){ function check_usergroup(){ function check_homedir(){ function check_username_exist(){ function check_username_notexist() { function check_user_disabled(){ function update_sshkey(){ if [ $# != 2 ];then check_root case "$1" in 'passwd') $ sudo chmod +x sftpusers.sh |
3.创建SFTP用户并测试
$ ./sftpusers.sh
代码如下 | 复制代码 |
1 Usage: ./sftpusers.sh {create|disable|enable|passwd|sshkey|delete} {username} |
创建用户
代码如下 | 复制代码 |
$ ./sftpusers.sh create facebook This script must be run as root $ sudo ./sftpusers.sh create facebook User facebook was created. $ id facebook uid=504(facebook) gid=503(sftpusers) groups=503(sftpusers) $ grep facebook /etc/passwd facebook:x:504:503:facebook sftp:/home/sftp/facebook:/sbin/nologin 禁用用户 $ sudo ./sftpusers.sh disable facebook Locking password for user facebook. |
修改用户密钥
代码如下 | 复制代码 |
$ sudo ./sftpusers.sh sshkey facebook User facebook ALREADY disabled. $ sudo ./sftpusers.sh enable facebook Unlocking password for user facebook. $ sudo ./sftpusers.sh sshkey facebook Input sshkey: ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA7g/9+vddcvZHpEBSLoNR3fCOuR0ZlyKBcmG7N facebook@us $ sudo ls -l /home/sftp/facebook/.ssh/authorized_keys -rw------- 1 facebook sftpusers 397 Sep 5 19:40 /home/sftp/facebook/.ssh/authorized_keys |
连接SFTP
代码如下 | 复制代码 |
$ sftp facebook@sftpserver Connecting to sftpserver... |
删除用户
代码如下 | 复制代码 |
$ sudo ./sftpusers.sh delete facebook Delete all the data and account of user facebook? [yes|no] yes $ sudo ./sftpusers.sh delete facebook User facebook NOT exist. $ id facebook id: facebook: No such user |