User Tools

Site Tools


ubuntu:sftp:script_to_create_a_sftp_user_to_access_only_home_directory

Ubuntu - SFTP - Script to Create a SFTP User to Access Only Home Directory

NOTE: This script will save the password in the account.txt file.


Go Home

cd /home

Create the accounts.txt file

sudo touch accounts.txt

Create the sftp shell setup script

createsftp.sh
#!/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

Make the script executable

sudo chmod +x createsftp.sh

To create an SFTP account

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

To Delete an SFTP Account

Delete the user

sudo deluser peter

returns:

Removing user `peter' ...
Warning: group `peter' has no more members.
Done.

Delete the sftp config lines

Delete the following lines from /etc/ssh/sshd_config:

/etc/ssh/sshd_config
Match User peter
ChrootDirectory /home/peter/
 ForceCommand internal-sftp
 AllowTCPForwarding no
 X11Forwarding no

Delete the home directory of the user

sudo rm -rf peter
ubuntu/sftp/script_to_create_a_sftp_user_to_access_only_home_directory.txt · Last modified: 2021/07/23 09:55 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki