76 lines
2.2 KiB
Bash
76 lines
2.2 KiB
Bash
#!/bin/bash
|
|
|
|
set -e # Exit immediately if a command exits with a non-zero status
|
|
|
|
LOG_FILE="/home/jelastic/add-sftp-user-addon/logs/script_output.log"
|
|
VERBOSE=1 # Set to 1 for verbose mode, 0 for normal mode
|
|
|
|
log() {
|
|
local filename=${2:-$LOG_FILE}
|
|
local timestamp=$(date +"%Y-%m-%d %H:%M:%S")
|
|
local message="$timestamp - $1"
|
|
if [ "$VERBOSE" -eq 1 ]; then
|
|
echo "$message" | tee -a $filename
|
|
else
|
|
echo "$message" >> $filename
|
|
fi
|
|
}
|
|
|
|
error_exit() {
|
|
log "ERROR: $1"
|
|
exit $2
|
|
}
|
|
|
|
# Generate random username and password
|
|
USERNAME=$1
|
|
PASSWORD=$2
|
|
|
|
# User's home directory
|
|
USER_HOME="/home/sftpusers/$USERNAME"
|
|
# The shared directory
|
|
ROOT_DIRECTORY="/var/www/webroot/ROOT"
|
|
|
|
log "Script started"
|
|
|
|
# Ensure the ROOT_DIRECTORY exists
|
|
[ ! -d "$ROOT_DIRECTORY" ] && error_exit "ROOT_DIRECTORY $ROOT_DIRECTORY does not exist." 2
|
|
|
|
# Get the group ownership of the ROOT_DIRECTORY
|
|
ROOT_GROUP=$(stat -c '%G' $ROOT_DIRECTORY)
|
|
|
|
# Check if user already exists
|
|
id "$USERNAME" &>/dev/null && error_exit "User $USERNAME already exists." 3
|
|
|
|
# Create user with their own directory under /home/sftpusers/
|
|
mkdir -p $USER_HOME
|
|
useradd -d $USER_HOME $USERNAME
|
|
echo "$USERNAME:$PASSWORD" | chpasswd
|
|
|
|
# Log to sftp-users.log
|
|
log "User $USERNAME created with home directory $USER_HOME" "/home/jelastic/add-sftp-user-addon/logs/sftp-users.log"
|
|
|
|
# Create a symlink in the user's directory pointing to the shared ROOT_DIRECTORY
|
|
ln -s $ROOT_DIRECTORY $USER_HOME/ROOT
|
|
log "Symlink created for $USERNAME pointing to $ROOT_DIRECTORY"
|
|
|
|
# Set user's group to the ROOT_GROUP
|
|
usermod -aG $ROOT_GROUP $USERNAME
|
|
log "$USERNAME added to group $ROOT_GROUP"
|
|
|
|
# Adjust permissions and ownership for the user's directory
|
|
chown $USERNAME:$ROOT_GROUP $USER_HOME
|
|
chmod 750 $USER_HOME
|
|
|
|
# Adjust permissions and ownership for the ROOT_DIRECTORY
|
|
chown -R :$ROOT_GROUP /var/www/webroot/ROOT/
|
|
find /var/www/webroot/ROOT/ -type d -exec chmod 770 {} \;
|
|
find /var/www/webroot/ROOT/ -type f -exec chmod 660 {} \;
|
|
|
|
# Set the SetGID bit on ROOT_DIRECTORY
|
|
chmod g+s $ROOT_DIRECTORY
|
|
|
|
HOSTNAME=$(hostname -f)
|
|
log "Script completed for user $USERNAME with hostname $HOSTNAME"
|
|
echo "{ \"USERNAME\": \"$USERNAME\", \"PASSWORD\": \"$PASSWORD\" }"
|
|
exit 0
|