#!/bin/bash
##########################
# web服务器配置虚拟ftp账号
# system: centos 6,7
# auth: dongdan
#########################

source $HOME/.bash_profile

ftp_dir=/etc/vsftpd
ftpuser=$1
ftpupass=$2
ftpuserhome=$3
guest_user=$4
vsftpd_user_conf=/etc/vsftpd/vsftpd_user_conf

if [ $# -ne 4 ];then
	echo "请输入正确的参数1、ftp用户名 2、ftp用户家目录 3、ftp用户密码 4、虚拟账户对应的系统账户"
	exit 1
fi

# 检测vsftpd是否安装
if [ ! -f /etc/init.d/vsftpd ];then
	echo "安装vsftpd..."
	yum install vsftpd -y > /dev/null 2>&1
	if [ $? -ne 0 ];then
		echo "vsftpd安装失败！"
		exit 1
	fi
fi

# 修改vsftpd配置文件
echo "修改ftp配置"
cd $ftp_dir
sed -i 's/anonymous_enable=YES/anonymous_enable=NO/' vsftpd.conf
sed -i 's/^pam_service_name=vsftpd$/pam_service_name=vsftpd.vu/' vsftpd.conf
sed -i 's/#chroot_local_user=YES/chroot_local_user=YES/' vsftpd.conf

grep "user_config_dir" $ftp_dir/vsftpd.conf > /dev/null 2>&1
if [ $? -ne 0 ];then	
	echo "
guest_enable=YES
anon_umask=022
user_config_dir=/etc/vsftpd/vsftpd_user_conf
max_clients=100
max_per_ip=20
	" >> vsftpd.conf
fi

# 添加虚拟账户
echo "$1
$3" >> login.txt

/usr/bin/which db_load > /dev/null 2>&1
if [ $? -ne 0 ];then
	echo "安装db_load ..."
	yum install db4-utils -y > /dev/null 2>&1
fi

db_load -T -t hash -f /etc/vsftpd/login.txt /etc/vsftpd/login.db
chmod 600 /etc/vsftpd/login.db

if [ ! -f /etc/pam.d/vsftpd.vu ];then
	echo "
auth    required        pam_userdb.so   db=/etc/vsftpd/login
account required        pam_userdb.so   db=/etc/vsftpd/login" >> /etc/pam.d/vsftpd.vu
fi

mkdir $vsftpd_user_conf -p
echo "
guest_username=$4
anon_world_readable_only=NO
anon_upload_enable=YES
anon_mkdir_write_enable=YES
local_root=$2
ftpd_banner=Welcome to user
anon_other_write_enable=yes
" >> $vsftpd_user_conf/$1

release_num=$(cat /etc/redhat-release |awk -F'release' '{print $2}'|cut -b 2)
if [ $release_num -eq 6 ];then
    service vsftpd restart
    chkconfig vsftpd on
    echo "ftp 安装完成！"
elif [ $release_num -eq 7 ];then
    echo "allow_writeable_chroot=YES" >> $ftp_dir/vsftpd.conf
    systemctl start vsftpd
    systemctl enable vsftpd
    echo "ftp 安装完成！"
fi

