SoFunction
Updated on 2025-03-02

Shell script to build an FTP server (vsftpd)


#!/bin/bash
# by liuhx 2013-Nov-04.
# Set the script for the ftp environment. The root directory of ftp is read-only, and the writable directory under it is writable

# The following four items can be customized
#ftp username
userName="test"
#ftp password
password="test"
# ftp root directory, do not add / at the end
ftp_dir="$HOME/ftp"
# Directory name of the directory that can be written
writable="writable"


# If sudo is not added, an error is prompted and exit
if [ "x$(id -u)" != x0 ]; then 
  echo "Error: please run this script with 'sudo'." 
  exit 1
fi

# Core tool, vsftpd. -y is to answer all prompts yes
sudo apt-get -y install vsftpd
# db-util is a tool used to generate a user list database
sudo apt-get -y install db-util

# References to the following steps/community/vsftpd#The_workshop
# Create a database of usernames and passwords, and record the usernames with odd numbers and even numbers
cd /tmp
printf "$userName\n$password\n" >
db_load -T -t hash -f
sudo cp -f /etc/
cd /etc
chmod 600
if [ ! -e ]; then
 sudo cp -f
fi

# Create a PAM file. Here-document of bash, directly output these contents overwrite the original file
(sudo cat <<EOF
auth       required     pam_userdb.so db=/etc/vsftpd-virtual-user
account    required     pam_userdb.so db=/etc/vsftpd-virtual-user
session    required     pam_loginuid.so
EOF
) > /

# Get the current username, you cannot use whoami or $LOGNAME, otherwise you will get root
owner=`who am i| awk '{print $1}'`

# Create a vsftpd configuration file.
(sudo cat <<EOF
listen=YES
anonymous_enable=NO
local_enable=YES
virtual_use_local_privs=YES
write_enable=YES
local_umask=000
dirmessage_enable=YES
use_localtime=YES
xferlog_enable=YES
connect_from_port_20=YES
chroot_local_user=YES
hide_ids=YES
secure_chroot_dir=/var/run/vsftpd/empty
pam_service_name=
guest_enable=YES
user_sub_token=$USER
rsa_cert_file=/etc/ssl/certs/
rsa_private_key_file=/etc/ssl/private/
EOF
) >
sudo echo "local_root=$ftp_dir" >>
# Virtual users need to be mapped to local users and set as themselves to avoid permission issues, but at the same time it also makes themselves unable to write the ftp root directory
sudo echo "guest_username=$owner" >>


# Set that each virtual user can only browse its root and subdirectories (otherwise, you can access the disk root directory).
# This will require that the root directory is not writable, so create a writable subdirectory
mkdir "$ftp_dir"
mkdir "$ftp_dir/$writable"
sudo chmod a-w "$ftp_dir"
sudo chown -R $owner:$owner $ftp_dir

sudo /etc//vsftpd restart