#!/bin/bash
# Check for root privileges
if [ "$(id -u)" -ne 0 ]; then
echo "This script must be run as root."
exit 1
fi
# Function to add a new SFTP user
add_sftp_user() {
local USERNAME=$1
sudo useradd -m -d /home/$USERNAME -s /sbin/nologin -G sftpusers $USERNAME
echo "Enter password for $USERNAME:"
sudo passwd $USERNAME
sudo mkdir /var/sftp/$USERNAME
sudo chown $USERNAME:sftpusers /var/sftp/$USERNAME
sudo chmod 700 /var/sftp/$USERNAME
}
# Creating a group if it doesn't exist
if ! getent group sftpusers > /dev/null; then
sudo groupadd sftpusers
fi
# Add multiple users in a loop
for USER in "$@"; do
add_sftp_user $USER
done
# Restart SSH service
sudo systemctl restart sshd
Save the script to a file, for example add_sftp_users.sh, make it executable, and run it with the usernames as arguments:
chmod +x add_sftp_users.sh
./add_sftp_users.sh user1 user2 user3
Steps to Update /etc/ssh/sshd_config (if needed)
Step 1: Open the Configuration File
You can open the SSH daemon configuration file using a text editor like nano:
sudo nano /etc/ssh/sshd_config
Step 2: Review Match Blocks for Deleted Users
Check for any user-specific or group-specific Match blocks that were added for SFTP users and ensure they are still applicable. For instance:
Match Group sftpusers
ChrootDirectory /sftp/%u
ForceCommand internal-sftp
AllowTcpForwarding no
X11Forwarding no
Step 3: Ensure the following lines are present and not commented out:
PasswordAuthentication yes
ChallengeResponseAuthentication no
UsePAM yes
If you've removed all users in the sftpusers group and no new users will be added, you may choose to remove or comment out this block. Otherwise, ensure the Match block is correctly aligned with the current users.
Step 4: Save Changes and Exit
After making necessary changes, save the file:
In nano, press CTRL + O to save and CTRL + X to exit.
Step 5: Restart SSH Service
After updating the configuration, restart the SSH service to apply the changes:
sudo systemctl restart sshd
Set the correct ownership and permissions for the Chroot directory and its parent directories:
sudo chown root:root /var/sftp
sudo chmod 755 /var/sftp
sudo chown root:root /var/sftp/{username}
sudo chmod 755 /var/sftp/{username}
sudo mkdir -p /var/sftp/{username}/uploads
sudo chown {username}:sftpusers /var/sftp/{username}/uploads
sudo chmod 755 /var/sftp/{username}/uploads
0 Comments