nico.fyi
    Published on

    How to create SFTP-only user in Ubuntu Server

    Authors

    When I was playing with Coolify, for no particular reason I wanted to create a user in my Ubuntu server that only had access to SFTP. I found some tutorials online but I thought it would be a good idea to write a script to do this.

    create-sftp-user.sh
    #!/bin/bash
    
    if [ $# -eq 0 ]; then
      echo "Please provide a username as an argument."
      exit 1
    fi
    
    username=$1
    
    sudo adduser --shell /bin/false --disabled-password --gecos "" $username
    
    echo "Enter the password for the user '$username':"
    read -s password
    echo
    
    echo "$username:$password" | sudo chpasswd
    
    sftp_directory="/var/sftp"
    user_directory="$sftp_directory/$username"
    sudo mkdir -p "$user_directory"
    sudo chown root:root "$sftp_directory"
    sudo chown $username:$username "$user_directory"
    sudo chmod 755 "$sftp_directory"
    sudo chmod 700 "$user_directory"
    
    sudo tee -a /etc/ssh/sshd_config > /dev/null <<EOL
    Match User $username
    	ForceCommand internal-sftp
    	PasswordAuthentication yes
    	ChrootDirectory $sftp_directory
    	PermitTunnel no
    	AllowAgentForwarding no
    	AllowTcpForwarding no
    	X11Forwarding no
    EOL
    
    sudo systemctl restart ssh
    
    echo "SFTP user '$username' created with the provided password and separate directory."
    

    To run the script, simply execute the following command: ./create-sftp-user.sh <username>. Replace <username> with the desired username. Then the script will prompt you to enter the password for the user.

    Then I thought it would also be a good idea to create a script to quickly delete the user and the associated directory. Here's the script:

    delete-sftp-user.sh
    #!/bin/bash
    
    if [ $# -eq 0 ]; then
      echo "Please provide a username as an argument."
      exit 1
    fi
    
    username=$1
    
    sudo deluser --remove-home $username
    
    user_directory="/var/sftp/$username"
    sudo rm -rf "$user_directory"
    
    sudo sed -i "/Match User $username/,/X11Forwarding no/d" /etc/ssh/sshd_config
    
    sudo systemctl restart ssh
    
    echo "SFTP user '$username' and associated resources have been deleted."
    

    Are you working in a team environment and your pull request process slows your team down? Then you have to grab a copy of my book, Pull Request Best Practices!