Mini Shell

Direktori : /opt/sharedrads/
Upload File :
Current File : //opt/sharedrads/check_domcount.sh

#!/bin/bash
# This Script checks /etc/userdomains for per user domain count and generates STRs if a user contains more than the threshold set in $DOMCOUNT Domains
# Debug mode (set to true for logging to file, false for sending email)
debug=true

# Log file path for debug mode
LOG_FILE="/var/log/domcount_checker.log"

# Domain Count Threshold
DOMCOUNT=$1

HOSTNAME=$(hostname | cut -d '.' -f1)

if ! [[ "$DOMCOUNT" =~ ^[0-9]+$ ]]; then
    echo "Error: DOMCOUNT argument is missing or not a number."
    exit 1
fi

# Check for --send flag to disable debug mode
if [[ "$2" == "--send" ]]; then
    debug=false
fi

# Email settings
EMAIL_RECIPIENT="str@imhadmin.net"
EMAIL_SUBJECT="User with High Domain Count Detected"

# Function to check if a user is suspended
function check_suspended() {
    local suspended=""
    if [ -f /var/cpanel/suspended/$1 ]; then
        local AGE=$(stat --format=%Y /var/cpanel/suspended/$1)
        AGE=$(($(date +%s)-AGE))
        AGE=$(($AGE/86400))
        suspended="SUSPENDED $AGE DAYS $(cat /var/cpanel/suspended/$1)"
    fi
    echo "$suspended"
}

# Log users with over $DOMCOUNT domains or send an email
process_user() {
    local user=$1
    local domain_count=$2
    local suspended_status=$(check_suspended "$user")
   
    if [ "$debug" = true ]; then
        # Generate Log
        echo "User $user with $domain_count domains detected. $suspended_status Logged for review." >> "$LOG_FILE"
    else
        # Send email
        echo "A user with more than $DOMCOUNT domains has been detected: $user with $domain_count domains on $HOSTNAME - $suspended_status Please review. You may run 'touch /home/$user/.imh/domcount' to exclude this user from future checks." | mail -s "$EMAIL_SUBJECT: $user" $EMAIL_RECIPIENT

    fi
}

# Check domain count and skip user if excluded
check_and_notify() {
    local user=$1
    local domain_count=$2
    local exclusion_file="/home/$user/.imh/domcount"

    # Skip if user is excluded
    if [ -f "$exclusion_file" ]; then
        echo "Skipping user $user due to exclusion file."
        return
    else
        echo "$exclusion_file No exclusion file found for user $user. Proceeding with domain count check..."
        # Act if domain count is greater than or equal to $DOMCOUNT
        if [ "$domain_count" -ge $DOMCOUNT ]; then
            process_user "$user" "$domain_count"
        fi
    fi
}

# Process /etc/userdomains to count domains per user
declare -A userdomains
while IFS=: read -r domain user; do
    user=$(echo "$user" | xargs)
    ((userdomains["$user"]++))
done < /etc/userdomains

# Check each user and manage notification
for user in "${!userdomains[@]}"; do
    check_and_notify "$user" "${userdomains[$user]}"
done

Zerion Mini Shell 1.0