Created
March 18, 2025 14:10
-
-
Save atomtigerzoo/22adff32b4bcc23eac7ba1309bd8122b to your computer and use it in GitHub Desktop.
Script to create a user for SFTPonly / chrooted access for deploys via sftp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# The group 'sftponly' needs to exist | |
# $ groupadd sftponly | |
# Update ssh to allow new group and use chroot | |
# $ nano /etc/ssh/sshd_config | |
# | |
# Match Group sftponly | |
# ChrootDirectory %h | |
# ForceCommand internal-sftp | |
# AllowTcpForwarding no | |
# X11Forwarding no | |
# | |
# check if the script is run as root | |
if [ "$(id -u)" -ne 0 ]; then | |
echo "This script must be run as root. Use: sudo $0 USERNAME" | |
exit 1 | |
fi | |
# check for username parameter | |
if [ "$#" -ne 1 ]; then | |
echo "Usage: sudo $0 USERNAME" | |
exit 1 | |
fi | |
USERNAME=$1 | |
GROUP="sftponly" | |
echo "Enter password for $USERNAME:" | |
read -s PASSWORD | |
echo "Confirm password:" | |
read -s PASSWORD_CONFIRM | |
if [ "$PASSWORD" != "$PASSWORD_CONFIRM" ]; then | |
echo "Passwords do not match. Exiting." | |
exit 1 | |
fi | |
# create user and home without shell access | |
useradd -g "$GROUP" -s /bin/false -m -d "/home/$USERNAME" "$USERNAME" | |
# set password | |
echo "$USERNAME:$PASSWORD" | chpasswd | |
# set correct permissions for chroot | |
chown root: "/home/$USERNAME" | |
chmod 755 "/home/$USERNAME" | |
# create child folder and set permissions | |
mkdir -p "/home/$USERNAME/public_html" | |
chmod 755 "/home/$USERNAME/public_html" | |
chown "$USERNAME:$GROUP" "/home/$USERNAME/public_html" | |
echo "User $USERNAME has been created and configured for SFTP-only access." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment