Last active
January 31, 2024 17:53
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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