NOTE: This script will save the password in the account.txt file.
cd /home
sudo touch accounts.txt
#!/bin/bash # This script automatically creates an SFTP Account and only allows access to the Home Directory. # Check that a username is provided. if [ $# -lt 1 ]; then echo "Please enter a username" echo "Usage: " $0 "peter" exit fi # Check if the username already exists. if id "$1" >/dev/null 2>&1; then echo "Username already exists" echo "Use a different username" exit fi # Generate a random password for SFTP. newuser=$1 randompw=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 10 | head -n 1) # Create the new user and assign the random password. useradd $newuser echo $newuser:$randompw | chpasswd # Set folder permissions. mkdir /home/$newuser chown root:root /home/$newuser sleep 2 mkdir /home/$newuser/sftproot sleep 2 chown $newuser:$newuser /home/$newuser/sftproot cat <<EOF >> /etc/ssh/sshd_config Match User $newuser ChrootDirectory /home/$newuser/ ForceCommand internal-sftp AllowTCPForwarding no X11Forwarding no EOF sleep 2 service ssh restart # New Username and Password to accounts.txt cat <<EOF >> /home/accounts.txt $newuser $randompw EOF echo "SFTP Account:" $newuser " has been created with password:" $randompw
sudo chmod +x createsftp.sh
sudo ./createsftp.sh peter
returns:
SFTP Account: peter has been created with password: ABC0123def
NOTE: The Password is also saved in the accounts.txt file.
cat account.txt
returns:
peter ABC0123def
sudo deluser peter
returns:
Removing user `peter' ... Warning: group `peter' has no more members. Done.
Delete the following lines from /etc/ssh/sshd_config:
Match User peter ChrootDirectory /home/peter/ ForceCommand internal-sftp AllowTCPForwarding no X11Forwarding no
sudo rm -rf peter