#!/bash/bash
# 文件名: RHEL-7_vsftpd_install.sh
# 作者: Shuhui

DATA_DIR=/data/ftp
KEY_DIR=/etc/vsftpd/.sslkey
VU_CONF_DIR=/etc/vsftpd/vu_conf_dir
GUEST_USER=ftpuser
LISTEN_PORT=60021
SIP_ADDR=$(curl ifconfig.io) # 2020/10/10 新增,解决DNAT环境中PASV数据传输问题，如阿里云
                                                       
DEMO_USER1=$1
RANDOM_PWD=$(date +%s|sha256sum|base64|head -c20)

if [[ $# -ne 1 ]]
then
    echo "Usage: $(basename $0 .sh) username"
    exit 1;
fi

# 安装软件包
yum -y install vsftpd db4-utils db4

# 创建 Guest user
id -u $GUEST_USER >/dev/null 2>&1
if [[ $? -ne 0 ]]
then
    useradd -s /sbin/nologin -d $DATA_DIR $GUEST_USER 
fi

# 创建目录
mkdir -pv {$DATA_DIR,$KEY_DIR,$VU_CONF_DIR}
chown $GUEST_USER:$GUEST_USER $DATA_DIR -R

# 生成证书
cd $KEY_DIR
if [[ ! -e vsftpd.pem ]]
then 
	openssl req -new -subj "/C=CN/ST=GuangDong/L=GuangZhou/O=Hello/OU=IT/CN=vqiu.cn" -x509 -nodes -out vsftpd.pem -keyout vsftpd.pem -days 3650
	chmod 0600 vsftpd.pem
fi

cd /etc/vsftpd/
# 生成一个 demo 用户 zhang3
echo -en "${DEMO_USER1}\n${RANDOM_PWD}\n" > vu_vsftpd.txt

# 生成 db 数据库
db_load -T -t hash -f vu_vsftpd.txt vu_vsftpd.db

if [[ -e vsftpd.conf ]]
then
    \mv vsftpd.conf vsftpd.conf.save
fi
cat > vsftpd.conf <<EOF
anonymous_enable=NO
local_enable=YES
write_enable=YES
dirmessage_enable=YES
ascii_upload_enable=YES
ascii_download_enable=YES
xferlog_enable=YES
chown_uploads=YES
xferlog_std_format=YES
data_connection_timeout=120
chroot_local_user=YES
listen=YES
listen_port=${LISTEN_PORT}
listen_ipv6=NO
tcp_wrappers=YES
pasv_enable=YES
pasv_address=${SIP_ADDR}
pasv_min_port=25000
pasv_max_port=30000
pam_service_name=vsftpd.vu
guest_enable=YES
guest_username=${GUEST_USER}
user_config_dir=${VU_CONF_DIR}
virtual_use_local_privs=YES
local_umask=002
anon_umask=002
file_open_mode=0775
ssl_enable=YES
ssl_tlsv1=YES
force_local_logins_ssl=yes
force_local_data_ssl=yes
rsa_cert_file=${KEY_DIR}/vsftpd.pem
ssl_ciphers=HIGH
allow_writeable_chroot=YES
EOF

cat > $VU_CONF_DIR/$DEMO_USER1 <<EOF
anon_world_readable_only=NO
write_enable=YES
local_umask=002
anon_upload_enable=YES
anon_mkdir_write_enable=YES
anon_other_write_enable=YES
local_root=${DATA_DIR}
EOF

cat > /etc/pam.d/vsftpd.vu <<EOF
auth required /lib64/security/pam_userdb.so db=/etc/vsftpd/vu_vsftpd crypt=hash
account required /lib64/security/pam_userdb.so db=/etc/vsftpd/vu_vsftpd crypt=hash
EOF

systemctl start vsftpd
systemctl enable vsftpd

echo -en "FTP user:\n${DEMO_USER1}\n${RANDOM_PWD}\n"
