BASH Script to add new SFTP user and setup permissions

This script adds a new SFTP user with only sftp access.  Refer to this post on setting up a SFTP server.

Download script

wget www.incredigeek.com/home/downloads/scripts/sftpUserAdd.sh

Make executable

chmod +x sftpUserAdd.sh

Run with the new user you want to create.

./sftpUserAdd.sh sftpUsername

You may need to edit the script and modify the location parameters.

#!/bin/bash
# Automatically setup and add SFTP user
# Script creates new user and setups permissions
newUser=$1
sftpDir="/sftp/"
if grep -q ${newUser} /etc/passwd ;then
echo ${newUser} Already exsists. Aborting!
exit 1
else
mkdir -p ${sftpDir}/${newUser}/files
useradd -g sftpusers -d ${sftpDir}/${newUser}/files -s /sbin/nologin ${newUser}
passwd ${newUser}
chown ${newUser}:sftpusers /sftp/CareMark/files
fi

Setup Secure FTP server on CentOS

Setup SFTP Server

When finished you’ll have a SFTP server setup that is configured so the users are in a chroot environment, and can not ssh, or telnet to the server.

Install SSH server if it is not already

yum install openssh-server openssh-client

Create group that is limited to sftp so they can’t ssh, scp etc.

groupadd sftpusers

Add chroot settings to /etc/ssh/sshd_config.  The %u is a variable, which is the users username.

Match Group sftpusers
ChrootDirectory /sftp/%u
ForceCommand internal-sftp

Make ftp directory

mkdir /sftp

Add SFTP user

useradd -g sftpusers -d /sftp -s /sbin/nologin newsftpuser

Create password for new user

passwd newsftpuser

Create directory for user

mkdir /sftp/newsftpuser

Create directory to put ftp files

mkdir /sftp/newsftpuser/files

Change permissions

chown newsftpuser:sftpusers /sftp/newsftpuser/files/

Restart sshd

systemctl restart sshd

Should be good to go.  Test it by logging in with your favorite FTP client.