Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Automate adding new SFTP chrooted accounts
#!/usr/bin/env bash
# Automate adding new SFTP accounts (chrooted)
# --------------------------------------------------------------------------------
#
if [ $# == 0 ]; then
echo "Usage: add-sftp-user EMAILS "
echo "Automates adding a SFTP user account, delagating all tasks and sending confirmation email."
else
# Main variables
emails=$@
home_dir="/ftp"
sftp_home="/home/sftpuser"
# Create account for each email passed
for email in ${emails[@]}; do
# Get username from email address and ask for name input
user=$(echo "$email" | awk -F"@" '{print $1}')
read -p "Name: " NAME
user_home="${sftp_home}/${user}"
echo "Adding user -- ${user}"
sudo useradd ${user} -c "${NAME}" -s /usr/libexec/openssh/sftp-server -d "${user_home}" -G sftpuser
echo "Creating chrooted home"
chrooted_home="${user_home}/ftp"
sudo mkdir ${chrooted_home}
sudo usermod -d /ftp ${user}
echo "Applying ownership and permissions for chrooted account"
sudo chown root:root ${user_home}
sudo chmod 755 ${user_home}
sudo chown ${user}:ftp ${chrooted_home}
sudo chmod 770 ${chrooted_home}
echo "Finished setting up account! Account created for: ${user}"
#===================================================================
echo "Sending email to ${user}"
MAILTO="${email}"
BC=""
SUBJECT="SFTP Account Created"
# Substitute variables in email template
BODY=$(sed -e "s/{USER}/${NAME}/g" < ~/templates/SFTPemail.txt)
BODY=$(echo -e $BODY | sed -e "s/{USERNAME}/${user}/g")
# Send email
echo -e "$BODY" | mail -s "$SUBJECT" -b "$BC" -r "$BC" $MAILTO
done
echo "DONE!"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment