Following script will create a SFTP user to access only home directory (Ubuntu 12x, 14x or 16x)
This script will save password in account.txt file.
Go to your home directory
cd /home
Create a account.txt file
sudo touch account.txt
Create a shell script and paste following script
nano createsftp.sh
#!/bin/bash
####
# This script automatically creates SFTP Account and allow only access to Home Directory
#
# Author: Asuk Nath
# Date: 11/20/15
#
###
# Check user name supplied or not
if [ $# -lt 1 ]; then
echo "Please supply a username"
echo "Example: " $0 "john"
exit
fi
# Check if username already exist
if id "$1" >/dev/null 2>&1; then
echo "Username Exists"
echo "Use different username"
exit
fi
# Declare local variable and generate random password for SFTP
newuser=$1
randompw=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 8 | head -n 1)
# Create new user and assign random password.
useradd $newuser
echo $newuser:$randompw | chpasswd
# Setting folder permission
echo "Please wait Applying Permission and setting Incoming folder"
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 account.txt
cat <<EOF >> /home/account.txt
$newuser $randompw
EOF
echo "SFTP Account:" $newuser "has been created with the password:" $randompw
Make this script executable
sudo chmod +x createsftp.sh
Command to create SFTP account
root@sftp:/home# sudo ./createsftp.sh user1
Please wait Applying Permission and setting Incoming folder
SFTP Account: user1 has been created with the password: Jtkxp0ZE
Password is also saved in account.txt file
cat account.txt
user1 6C215q3l
Delete SFTP account
root@sftp:/home# sudo deluser user1
Removing user `user1' ...
Warning: group `user1' has no more members.
Done.
Also you need to delete following lines from sshd_config file
Edit /etc/ssh/sshd_config
sudo nano /etc/ssh/sshd_config
Delete following lines
Match User user1
ChrootDirectory /home/user1/
ForceCommand internal-sftp
AllowTCPForwarding no
X11Forwarding no
Delete user’s home directory
sudo rm -rf user1