Skip to content

Instantly share code, notes, and snippets.

@chris-kobrzak
Last active January 31, 2024 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chris-kobrzak/9575f2400ceefbbd83e15925ed03a692 to your computer and use it in GitHub Desktop.
Save chris-kobrzak/9575f2400ceefbbd83e15925ed03a692 to your computer and use it in GitHub Desktop.
Shell script for detecting Linux processes consuming extensive amounts of processing power. Intended to be run on schedule.
#!/usr/bin/env bash
# 95% CPU utilisation
threshold=0.95
log_file="/var/log/kill-high-cpu-processes.log"
get_process_info() {
process_id=$1
ps -p "$process_id" -o pid,ppid,cmd,%cpu,%mem,stat --no-header | awk '{$1=$1};1'
}
high_cpu_processes=$(ps -eo pid,%cpu --sort=-%cpu | awk -v threshold="$threshold" '$2 > threshold {print $1}')
if [ -z "$high_cpu_processes" ]; then
exit
fi
# Log timestamp and processes to the file
echo "$(date +"%Y-%m-%d %H:%M:%S") - High CPU processes: $high_cpu_processes" >> "$log_file"
# Kill offending processes
for pid in $high_cpu_processes; do
process_info=$(get_process_info "$pid")
echo "$(date +"%Y-%m-%d %H:%M:%S") - Killing process $process_info..." >> "$log_file"
kill -9 "$pid"
echo "$(date +"%Y-%m-%d %H:%M:%S") - Process $pid killed." >> "$log_file"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment