Centos7 vsftpd 基于MySQL的虚拟账户认证

实验环境: 两台虚拟机的防火墙和SELinux都已关闭

角色 IP
vsftpd 192.168.148.7
mysql 192.168.148.17
系统账户 用户主目录
vuser /data/ftproot
虚拟账户 密码 用户主目录
ftp1 centos /data/ftproot/ftp1
ftp2 redhat /data/ftproot/ftp2

mysql服务器添加用户数据库

[root@localhost ~]# yum -y install mariadb-server
[root@localhost ~]#  systemctl start mariadb

[root@localhost ~]# vim vsftpd.sql
CREATE DATABASE vsftpd;
USE vsftpd

CREATE TABLE vuser (
id int(10) AUTO_INCREMENT PRIMARY KEY,
username char(30) BINARY NOT NULL,
password char(50) BINARY NOT NULL
);

insert into vuser(username,password)values('ftp1',password('centos')),('ftp2',password('redhat'));
grant select on vsftpd.vuser to vsftpd@'192.168.148.7' identified by 'centos';

[root@localhost ~]# mysql < vsftpd.sql 

vsftpd配置虚拟账户

[root@localhost ~]# yum -y install vsftpd
# 创建虚拟账户 ftp1, ftp2的用户目录和上传目录
[root@localhost ~]# mkdir -p /data/ftproot/ftp{1,2}/upload
[root@localhost ~]# touch /data/ftproot/ftp1/ftp1
[root@localhost ~]# touch /data/ftproot/ftp2/ftp2

# 创建虚拟账户映射的系统账号 vuser
[root@localhost ~]# useradd -r -s /sbin/nologin -d /data/ftproot vuser

# 修改配置文件,注释默认的 pam设置,添加如下配置
[root@localhost ~]# vim /etc/vsftpd/vsftpd.conf 
#pam_service_name=vsftpd
pam_service_name=vsftpd.mysql
guest_enable=YES
guest_username=vuser
user_config_dir=/etc/vsftpd/vusers.d

#添加虚拟账户配置文件
[root@localhost ~]# mkdir /etc/vsftpd/vusers.d
[root@localhost ~]# vim /etc/vsftpd/vusers.d/ftp1
anon_upload_enable=YES
anon_mkdir_write_enable=YES
anon_other_write_enable=YES
anon_umask=022
local_root=/data/ftproot/ftp1

[root@localhost ~]# vim /etc/vsftpd/vusersd.d/ftp2
anon_upload_enable=YES
anon_mkdir_write_enable=YES
anon_other_write_enable=YES
anon_umask=022
local_root=/data/ftproot/ftp2

# 下载 pam_mysql 下载地址 http://repo.iotti.biz/CentOS/7/x86_64/pam_mysql-0.8.1-0.22.el7.lux.x86_64.rpm
[root@localhost ~]# rpm -iv pam_mysql-0.8.1-0.22.el7.lux.x86_64.rpm

#编写vsftpd.mysql文件
[root@localhost ~]# vim /etc/pam.d/vsftpd.mysql
auth required pam_mysql.so user=vsftpd passwd=centos host=192.168.148.17  db=vsftpd table=vuser usercolumn=username passwdcolumn=password crypt=2
account required pam_mysql.so user=vsftpd passwd=centos host=192.168.148.17 db=vsftpd table=vuser usercolumn=username passwdcolumn=password crypt=2

# 启动服务
[root@localhost ~]# systemctl start vsftpd

MySQL服务器作客户端测试虚拟账户

# 安装客户端程序
[root@localhost ~]# yum -y install lftp
# 指定用户名,密码
[root@localhost ~]# lftp -u ftp1,centos 192.168.148.7
lftp ftp1@192.168.148.7:~> ls
-rw-r--r--    1 0        0               0 May 17 07:20 ftp1
drwxr-xr-x    2 0        0               6 May 17 07:04 upload
lftp ftp1@192.168.148.7:/> quit

[root@localhost ~]# lftp -u ftp2,redhat 192.168.148.7
lftp ftp2@192.168.148.7:~> ls
-rw-r--r--    1 0        0               0 May 17 07:20 ftp2
drwxr-xr-x    2 0        0               6 May 17 07:04 upload
lftp ftp2@192.168.148.7:/> bye