vsftpd本地用户模式部署

发布时间 2023-09-12 13:59:39作者: 背对背依靠
#/bin/bash

if [ $(id -u) -ne 0  ];then
    echo "需要root用户执行该脚本";exit 1
fi

# release
if grep -qi 'centos' /etc/os-release; then
    OS='centos'
elif grep -qi 'ubuntu' /etc/os-release; then
    OS='ubuntu'
else
    echo "此脚本仅适用于CentOS或Ubuntu";exit 1
fi

# installed
if [ "$OS" = "ubuntu" ];then
    if ! dpkg-query --show --showformat='${Status}' vsftpd | grep -q  "install ok installed" ;then
       echo "请先安装vsftpd服务";exit 1
    fi
else
    if ! rpm -q vsftpd &> /dev/null ; then
        echo "请先安装vsftpd服务";exit 1
    fi
fi

# useradd
echo -n "Please enter user name (default: ftpadmin): "
read user_name
user_name=${user_name:-ftpadmin}

echo -n "Please enter user password (default: Abc123): "
read user_passwd
user_passwd=${user_passwd:-Abc123}

echo -n "Please enter data dir (default: /ftpdata): "
read data_dir
data_dir=${data_dir:-/ftpdata}

if ! id ${user_name} &> /dev/null ;then
    useradd -m -d "${data_dir}" ${user_name}
    echo "${user_name}:${user_passwd}" | chpasswd
fi

chown -R ${User_Name}:${User_Name}  "${data_dir}"

# config
# [^ ]表示非空格的意思 
conf_file=$(systemctl cat vsftpd | grep -o "/[^ ]*\.conf")

cat >  ${conf_file} <<EOF
listen=NO
listen_ipv6=YES

# 禁用匿名用户模式
anonymous_enable=NO

# 启用本地用户模式
local_enable=YES
# 允许本地用户上传文件
write_enable=YES
# 上传文件的umask
local_umask=022
# 指定用户登录进来所在的目录
local_root=${data_dir}
# 允许对根目录有写权限
allow_writeable_chroot=YES
# 禁锢用户不能离开自己的家目录
chroot_local_user=YES

# user_list中的用户允许登录
userlist_enable=YES
# 指定user_list文件路径
userlist_file=/etc/vsftpd.user_list
# 如为YES,表示禁止列表中的用户访问FTP服务器
userlist_deny=NO

# 是否激活目录欢迎信息功能
dirmessage_enable=YES

# 使用本地时间
use_localtime=YES

xferlog_enable=YES

connect_from_port_20=YES

secure_chroot_dir=/var/run/vsftpd/empty

#  设置 PAM 外挂模块提供的认证服务所使用的配置文件名
pam_service_name=vsftpd
rsa_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
rsa_private_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
ssl_enable=NO

EOF

if [ ! -d "/var/run/vsftpd/empty" ];then
    mkdir -p /var/run/vsftpd/empty
fi

echo ${user_name} > /etc/vsftpd.user_list

systemctl enable vsftpd.service &> /dev/null

if systemctl restart vsftpd.service ;then
    echo "vsftpd 配置成功"
fi

echo -e "登录用户名: ${user_name}"
echo -e "登录密码: ${user_passwd}"
echo -e "数据目录: ${data_dir}"