add-sftp-user/add-sftp.sh

70 lines
2.1 KiB
Bash
Raw Normal View History

2023-10-26 15:54:56 +00:00
#!/bin/bash
LOG_FILE="/home/jelastic/add-sftp-user-addon/logs/script_output.log"
echo "Script started" >> $LOG_FILE
# Generate random username and password
2023-10-30 17:09:45 +00:00
USERNAME=$1
PASSWORD=$2
2023-10-26 15:54:56 +00:00
2023-10-30 16:13:29 +00:00
# User's home directory
USER_HOME="/home/$USERNAME"
# The shared directory
ROOT_DIRECTORY="/var/www/webroot/ROOT"
# Get the group ownership of the ROOT_DIRECTORY
ROOT_GROUP=$(stat -c '%G' $ROOT_DIRECTORY)
2023-10-26 15:54:56 +00:00
# Ensure the ROOT_DIRECTORY exists
if [ ! -d "$ROOT_DIRECTORY" ]; then
echo "ROOT_DIRECTORY $ROOT_DIRECTORY does not exist." >> $LOG_FILE
exit 1
fi
2023-10-26 15:54:56 +00:00
# Check if user already exists
if id "$USERNAME" &>/dev/null; then
echo "User $USERNAME already exists." >> $LOG_FILE
2023-10-26 15:54:56 +00:00
exit 1
fi
2023-10-30 16:13:29 +00:00
# Create user with their own home directory
useradd -m $USERNAME
2023-10-26 15:54:56 +00:00
if [ $? -ne 0 ]; then
echo "Failed to create user $USERNAME." >> $LOG_FILE
exit 1
2023-10-26 15:54:56 +00:00
fi
echo "$USERNAME:$PASSWORD" | chpasswd
2023-10-30 16:13:29 +00:00
# Create a symlink in the user's home directory pointing to the shared ROOT_DIRECTORY
ln -s $ROOT_DIRECTORY $USER_HOME/ROOT
if [ $? -ne 0 ]; then
echo "Failed to create symlink for $USERNAME." >> $LOG_FILE
exit 1
fi
echo "Symlink created for $USERNAME pointing to $ROOT_DIRECTORY" >> $LOG_FILE
2023-10-27 16:19:22 +00:00
2023-10-30 16:13:29 +00:00
# Set user's group to the ROOT_GROUP and any other groups as needed (e.g., root)
usermod -aG $ROOT_GROUP,root $USERNAME
if [ $? -ne 0 ]; then
echo "Failed to modify groups for $USERNAME." >> $LOG_FILE
exit 1
fi
echo "$USERNAME added to groups $ROOT_GROUP and root" >> $LOG_FILE
2023-10-26 15:54:56 +00:00
# Check if the user-specific directory already exists
if [ ! -d "$USER_SPECIFIC_DIR" ]; then
# Create a user-specific directory inside ROOT_DIRECTORY
mkdir $USER_SPECIFIC_DIR
chown $USERNAME:$ROOT_GROUP $USER_SPECIFIC_DIR
chmod 750 $USER_SPECIFIC_DIR # Owner has rwx, group has r-x, others have no permissions
else
echo "User-specific directory $USER_SPECIFIC_DIR already exists." >> $LOG_FILE
fi
# Set the SetGID bit on ROOT_DIRECTORY
chmod g+s $ROOT_DIRECTORY
2023-10-30 13:13:03 +00:00
HOSTNAME=$(hostname -f)
echo "Script completed for user $USERNAME with hostname $HOSTNAME" >> $LOG_FILE
2023-10-30 17:09:45 +00:00
echo "{ \"USERNAME\": \"$USERNAME\", \"PASSWORD\": \"$PASSWORD\" }"