add-sftp-user/add-sftp.sh

82 lines
2.2 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"
2023-11-01 06:42:52 +00:00
VERBOSE=1 # Set to 1 for verbose mode, 0 for normal mode
2023-11-01 06:42:52 +00:00
log() {
local timestamp=$(date +"%Y-%m-%d %H:%M:%S")
echo "$timestamp - $1" >> $LOG_FILE
if [ "$VERBOSE" -eq 1 ]; then
echo "$timestamp - $1"
fi
}
error_exit() {
log "ERROR: $1"
exit $2
2023-11-01 06:42:52 +00:00
}
# 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/sftpusers/$USERNAME"
2023-10-30 16:13:29 +00:00
# The shared directory
ROOT_DIRECTORY="/var/www/webroot/ROOT"
2023-11-01 06:42:52 +00:00
log "Script started"
2023-10-26 15:54:56 +00:00
# Ensure the ROOT_DIRECTORY exists
if [ ! -d "$ROOT_DIRECTORY" ]; then
error_exit "ROOT_DIRECTORY $ROOT_DIRECTORY does not exist." 2
fi
# Get the group ownership of the ROOT_DIRECTORY
2023-11-01 06:42:52 +00:00
ROOT_GROUP=$(stat -c '%G' $ROOT_DIRECTORY)
2023-10-26 15:54:56 +00:00
# Check if user already exists
if id "$USERNAME" &>/dev/null; then
2023-11-01 06:42:52 +00:00
log "ERROR: User $USERNAME already exists."
exit 3
2023-10-26 15:54:56 +00:00
fi
# Create user with their own directory under /home/sftpusers/
mkdir -p $USER_HOME
useradd -d $USER_HOME $USERNAME
2023-10-26 15:54:56 +00:00
if [ $? -ne 0 ]; then
error_exit "Failed to create user $USERNAME." 4
2023-10-26 15:54:56 +00:00
fi
echo "$USERNAME:$PASSWORD" | chpasswd
# Create a symlink in the user's directory pointing to the shared ROOT_DIRECTORY
2023-10-30 16:13:29 +00:00
ln -s $ROOT_DIRECTORY $USER_HOME/ROOT
if [ $? -ne 0 ]; then
error_exit "Failed to create symlink for $USERNAME." 5
fi
2023-11-01 06:42:52 +00:00
log "Symlink created for $USERNAME pointing to $ROOT_DIRECTORY"
2023-10-27 16:19:22 +00:00
2023-11-01 06:42:52 +00:00
# Set user's group to the ROOT_GROUP
usermod -aG $ROOT_GROUP $USERNAME
if [ $? -ne 0 ]; then
error_exit "Failed to modify groups for $USERNAME." 6
fi
2023-11-01 06:42:52 +00:00
log "$USERNAME added to group $ROOT_GROUP"
2023-10-26 15:54:56 +00:00
# Adjust permissions and ownership for the user's directory
chown $USERNAME:$ROOT_GROUP $USER_HOME
chmod 750 $USER_HOME # Owner has rwx, group has r-x, others have no permissions
2023-11-01 06:42:52 +00:00
# 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 {} \; # For directories
find /var/www/webroot/ROOT/ -type f -exec chmod 660 {} \; # For files
# Set the SetGID bit on ROOT_DIRECTORY
chmod g+s $ROOT_DIRECTORY
2023-10-30 13:13:03 +00:00
HOSTNAME=$(hostname -f)
2023-11-01 06:42:52 +00:00
log "Script completed for user $USERNAME with hostname $HOSTNAME"
2023-10-30 17:09:45 +00:00
echo "{ \"USERNAME\": \"$USERNAME\", \"PASSWORD\": \"$PASSWORD\" }"
exit 0