Wednesday, December 22, 2010

SFTP with OpenSSH User Setup made easy

I have explained before how to get SFTP working using OpenSSH.

Let me go an extra mile now and share a simple bash script that creates a user, assigns a password, sets a maximum number of files (and allowed size) and allows *just* SFTP access. Here is how you do so from a single command line (I tested this time in Ubuntu / Debian):
sudo  /path/to/addSftpUser.sh 'testUser' 'testPassword'


Here is the script code:
#!/bin/bash
#
# @fileName: addSftpUser.sh:
# @description: Creates an SFTP user
# @author: Nestor Urquiza
# @date: Dec 22, 2010
#

#
# Constants
#
ALLOWED_KB=100000
ALLOWED_FILES=1000

#
# Functions
#
function usage {
  echo "Usage - $0 user password"
  exit 1
}

#
# Main program
#
if [ $# -lt 2 ]
then
        usage
fi
USER=$1
PASSWORD=$2
useradd -d /home/$USER -s /bin/false -m $USER
usermod -g sftponly $USER
sudo usermod -p `mkpasswd $PASSWORD` $USER
chown root:root /home/$USER
chmod 755 /home/$USER
mkdir /home/$USER/$USER
chown $USER:$USER /home/$USER/$USER
chmod 755 /home/$USER/$USER
#Quotas: Feel free to remove if you do not need to limit uploads
setquota -u $USER $ALLOWED_KB $ALLOWED_KB $ALLOWED_FILES $ALLOWED_FILES -a /


You must be sure the user cannot SSH into the box:
$ ssh testUser@192.168.3.161
testUser@192.168.3.161's password: 
This service allows sftp connections only.
Connection to 192.168.0.161 closed.
$ 

You want to be sure the user can use SFTP
$ sftp testUser@192.168.3.161
Connecting to 192.168.3.161...
testUser@192.168.3.161's password: 
sftp> exit

No comments:

Followers