Add SSH admin capabilities - WP Cli

main
Anthony 2023-11-03 22:35:15 +08:00
parent 2e37b432ec
commit 27b700452f
1 changed files with 55 additions and 11 deletions

View File

@ -1,16 +1,26 @@
#!/bin/bash
LOG_FILE="/home/jelastic/add-sftp-user-addon/logs/script_output.log"
VERBOSE=1
DEBUG=${4:-0} # Set to 1 to enable debug logging, controlled by 4th argument
log() {
local filename=${2:-$LOG_FILE}
local level=${1:-INFO}
local message=${2}
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
echo "$timestamp [$level] $message" | tee -a $LOG_FILE
}
log_error() {
log "ERROR" "$1"
}
log_warning() {
log "WARNING" "$1"
}
log_debug() {
if [ "$DEBUG" -eq 1 ]; then
log "DEBUG" "$1"
fi
}
@ -21,22 +31,56 @@ generate_username() {
USERNAME=$1
PASSWORD=$2
SSH_ENABLED=$3
log "Script started"
# Check if user already exists, if yes generate a new one
while id "$USERNAME" &>/dev/null; do
USERNAME=$(generate_username)
log_warning "Username $USERNAME already exists, generating a new username."
done
USER_HOME="/home/sftpusers/$USERNAME"
ROOT_DIRECTORY="/var/www/webroot/ROOT"
ROOT_GROUP=$(stat -c '%G' $ROOT_DIRECTORY)
log "Script started"
# Create the wp-admins group if it doesn't exist
if ! grep -q "^wp-admins:" /etc/group; then
if groupadd wp-admins; then
log "Group wp-admins created successfully."
else
log_error "Failed to create group wp-admins."
exit 1
fi
fi
[ ! -d "$ROOT_DIRECTORY" ] && { log "ERROR: ROOT_DIRECTORY $ROOT_DIRECTORY does not exist."; exit 2; }
if ! useradd -d $USER_HOME $USERNAME; then
log_error "Failed to create user $USERNAME."
exit 1
fi
# Enable SSH access if requested
if [ "$SSH_ENABLED" == "true" ]; then
usermod -s /bin/bash $USERNAME
usermod -aG wp-admins $USERNAME # Add user to wp-admins group
# Ensure WP-CLI is installed
if ! command -v wp &> /dev/null; then
if curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar &&
chmod +x wp-cli.phar &&
mv wp-cli.phar /usr/local/bin/wp; then
log "WP-CLI installed successfully."
else
log_error "Failed to install WP-CLI."
exit 1
fi
fi
fi
[ ! -d "$ROOT_DIRECTORY" ] && { log_error "ROOT_DIRECTORY $ROOT_DIRECTORY does not exist."; exit 2; }
mkdir -p $USER_HOME
useradd -d $USER_HOME $USERNAME
echo "$USERNAME:$PASSWORD" | chpasswd
log "User $USERNAME created with home directory $USER_HOME"
@ -60,4 +104,4 @@ log "Script completed for user $USERNAME"
# Output the created username and password
echo "export CREATED_USERNAME=$USERNAME" >> /etc/profile
echo "export CREATED_PASSWORD=$PASSWORD" >> /etc/profile
echo "export CREATED_PASSWORD=$PASSWORD" >> /etc/profile