Skip to main content
< All Topics
Print

High CPU Killer – cPanel

Table of Contents

Script: kill_high_cpu_processes.sh

#!/bin/bash

# Variables
THRESHOLD=25
LOG_FILE="/var/log/kill_high_cpu_processes.log"

# Function to log and kill a process
kill_process() {
    local pid=$1
    local user=$2
    local cpu=$3

    echo "$(date): Killing process $pid (User: $user CPU: $cpu%)" | tee -a "$LOG_FILE"
    kill -9 "$pid"
}

# Main function
check_and_kill() {
    echo "$(date): Checking CPU usage..." | tee -a "$LOG_FILE"

    # Find processes exceeding the threshold
    ps -eo piduser%cpu --sort=-%cpu | awk -v threshold="$THRESHOLD" '
    NR>1 && $3 > threshold && $2 != "root" && $2 != "nobody" && $2 != "wp-toolkit" && $2 != "mysql"' |
    while read -r pid user cpu; do
        echo "$(date): Found high CPU process - PID: $pid User: $user CPU: $cpu%" | tee -a "$LOG_FILE"
        kill_process "$pid" "$user" "$cpu"
    done
}

# Run the check
check_and_kill

Instructions:

  1. Save the Script: Save it as kill_high_cpu_processes.sh.
  2. Make It Executable:bashCopyEditchmod +x kill_high_cpu_processes.sh
  3. Run the Script:bashCopyEditsudo ./kill_high_cpu_processes.sh
  4. Automate It (Optional): Use cron for periodic execution:bashCopyEditcrontab -e Add:bashCopyEdit* * * * * /path/to/kill_high_cpu_processes.sh

Fix:

  1. Check File Format: Ensure the script is saved in the correct format with Unix-style line endings. If you’re editing the script on Windows convert the line endings to Unix format. Use dos2unix to fix this:bashCopyEditsudo apt install dos2unix dos2unix kill_high_cpu_processes.sh
  2. Ensure the Shebang Line is Correct: Open the script and ensure the first line is:bashCopyEdit#!/bin/bash This tells the system to use bash to interpret the script.
  3. Verify the Path to Bash: Confirm the path to the Bash interpreter:bashCopyEditwhich bash If the output is /bin/bash the shebang line is correct. Otherwise update it to the appropriate path.
  4. Set Executable Permissions: Make sure the script has executable permissions:bashCopyEditchmod +x kill_high_cpu_processes.sh
  5. Run the Script: Execute the script again:bashCopyEditsudo ./kill_high_cpu_processes.sh

Check Execution:

If the script still doesn’t work try running it explicitly with Bash:

bashCopyEditbash ./kill_high_cpu_processes.sh

Table of Contents