add-sftp-user/add-sftp.sh

52 lines
1.5 KiB
Bash

#!/bin/bash
LOG_FILE="/home/jelastic/add-sftp-user-addon/logs/script_output.log"
echo "Script started" >> $LOG_FILE
# Generate random username and password
USERNAME="user$(shuf -i 10000-99999 -n 1)"
PASSWORD=$(openssl rand -base64 12)
# 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)
# Check if user already exists
if id "$USERNAME" &>/dev/null; then
echo "User $USERNAME already exists." >> $LOG_FILE
exit 1
fi
# Create user with their own home directory
useradd -m $USERNAME
if [ $? -ne 0 ]; then
echo "Failed to create user $USERNAME." >> $LOG_FILE
exit 1
fi
echo "$USERNAME:$PASSWORD" | chpasswd
# 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
# 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
HOSTNAME=$(hostname -f)
echo "Script completed for user $USERNAME with hostname $HOSTNAME" >> $LOG_FILE
echo "USERNAME:$USERNAME"
echo "PASSWORD:$PASSWORD"