Search FAQ...
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:
- Save the Script: Save it as
kill_high_cpu_processes.sh. - Make It Executable:bashCopyEdit
chmod +x kill_high_cpu_processes.sh - Run the Script:bashCopyEdit
sudo ./kill_high_cpu_processes.sh - Automate It (Optional): Use
cronfor periodic execution:bashCopyEditcrontab -eAdd:bashCopyEdit* * * * * /path/to/kill_high_cpu_processes.sh
Fix:
- 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
dos2unixto fix this:bashCopyEditsudo apt install dos2unix dos2unix kill_high_cpu_processes.sh - Ensure the Shebang Line is Correct: Open the script and ensure the first line is:bashCopyEdit
#!/bin/bashThis tells the system to usebashto interpret the script. - Verify the Path to Bash: Confirm the path to the Bash interpreter:bashCopyEdit
which bashIf the output is/bin/bashthe shebang line is correct. Otherwise update it to the appropriate path. - Set Executable Permissions: Make sure the script has executable permissions:bashCopyEdit
chmod +x kill_high_cpu_processes.sh - Run the Script: Execute the script again:bashCopyEdit
sudo ./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