Skip to content

Instantly share code, notes, and snippets.

@hkboujrida
Last active December 20, 2022 11:39
Show Gist options
  • Save hkboujrida/1cfb82c30a5b45058b3d741ff042ca4b to your computer and use it in GitHub Desktop.
Save hkboujrida/1cfb82c30a5b45058b3d741ff042ca4b to your computer and use it in GitHub Desktop.
#!/bin/bash
# example : refresh_ftp_users.sh -t ftp
# This script is used to refresh the ftp users
# it reads the users in the "ftpusers group"
# and creates the users in the ftpusers file
# read ftp type variable form the command line with -t or --type
# if no variable is passed then set it to "ftp"
# set USERS variable from the ftpusers group
# if type equals ftps then FTP_USERFILE is /etc/vsftpd-ftps.userlist else /etc/vsftpd-ftp.userlist
FTP_USERFILE=/etc/vsftpd-ftp.userlist
if [ "$1" = "-t" ] || [ "$1" = "--type" ]; then
if [ "$2" = "ftps" ]; then
FTP_USERFILE=/etc/vsftpd-ftps.userlist
fi
fi
# # if type equals ftps then SERVICE_NAME is vsftpd-ftps.service else vsftpd-ftps.service
SERVICE_NAME=vsftpd.service
if [ "$1" = "-t" ] || [ "$1" = "--type" ]; then
if [ "$2" = "ftps" ]; then
SERVICE_NAME=vsftpd-ftps.service
fi
fi
# # if type equals ftps then GROUP_NAME is ftpsusers else ftpusers
GROUP_NAME=ftpusers
if [ "$1" = "-t" ] || [ "$1" = "--type" ]; then
if [ "$2" = "ftps" ]; then
GROUP_NAME=ftpsusers
fi
fi
NEED_TO_RESTART=0
USERS=$(cat /etc/group | grep $GROUP_NAME | cut -d: -f4)
# split USERS by comma
USERS=($(echo $USERS | tr "," "\n"))
# loop through the users
for USER in ${USERS[@]}; do
echo "Checking user $USER"
# if user doesn't exist in the userlist file add it
# read $USER $FTP_USERFILE file into an array
USERS_IN_FILE=($(cat $FTP_USERFILE))
# if user doesn't exist in the USERS_IN_FILE
if [[ ! " ${USERS_IN_FILE[@]} " =~ " ${USER} " ]]; then
echo "Adding user $USER"
echo $USER >>$FTP_USERFILE
echo "User $USER added to $FTP_USERFILE"
mkdir -p /home/$USER/ftp
chown nobody:nogroup /home/$USER/ftp
chmod a-w /home/$USER/ftp
mkdir -p /home/$USER/ftp/files
chown $USER:$GROUP_NAME /home/$USER/ftp/files
NEED_TO_RESTART=1
fi
done
# check if vsftpd connection are open
# if no then restart the service
# if yes wait 2 minutes and check again
echo "Checking if vsftpd connections are open"
CONNECTIONS=$(lsof -i TCP -P -n | grep vsftpd | grep ESTABLISHED | wc -l)
if [ $NEED_TO_RESTART -eq 1 ]; then
while [ $CONNECTIONS -gt 0 ]; do
echo "Waiting 2 minutes for vsftpd connections to close"
sleep 120
CONNECTIONS=$(lsof -i TCP -P -n | grep vsftpd | grep ESTABLISHED | wc -l)
done
systemctl restart $SERVICE_NAME
fi
echo "Done"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment