Skip to content

Instantly share code, notes, and snippets.

@abdellatifLabr
Created October 13, 2024 21:05
Show Gist options
  • Save abdellatifLabr/737e654afe1c015e0dc7b0733f23ec81 to your computer and use it in GitHub Desktop.
Save abdellatifLabr/737e654afe1c015e0dc7b0733f23ec81 to your computer and use it in GitHub Desktop.
#! /bin/sh
get_meminfo_value() {
echo $(echo "$1" | grep -w "$2" | tr -s " " | cut -d ' ' -f 2)
}
mem_util() {
local meminfo="$(cat /proc/meminfo)"
local total=$(get_meminfo_value "$meminfo" MemTotal)
local free=$(get_meminfo_value "$meminfo" MemFree)
local buffers=$(get_meminfo_value "$meminfo" Buffers)
local cached=$(get_meminfo_value "$meminfo" Cached)
local used=$((total - free - buffers - cached))
local used_percent=$((used * 100 / total))
echo $used_percent
}
cpu_util() {
cpu1=$(grep '^cpu ' < /proc/stat)
idle1=$(echo $cpu1 | awk '{print $5}')
total1=$(echo $cpu1 | awk '{print $2+$3+$4+$5+$6+$7+$8+$9+$10}')
sleep 1
cpu2=$(grep '^cpu ' < /proc/stat)
idle2=$(echo $cpu2 | awk '{print $5}')
total2=$(echo $cpu2 | awk '{print $2+$3+$4+$5+$6+$7+$8+$9+$10}')
idle_delta=$((idle2 - idle1))
total_delta=$((total2 - total1))
cpu_util=$((100 * (total_delta - idle_delta) / total_delta))
echo $cpu_util
}
BOT_TOKEN="<telegram-bot-token>"
CHAT_ID="<telegram-chat-id>"
SAMPLE_RATE=5
CPU_THRESHOLD=80
MEM_THRESHOLD=80
send_telegram_msg() {
curl -s -X POST "https://api.telegram.org/bot$BOT_TOKEN/sendMessage" \
-d chat_id="$CHAT_ID" \
-d text="$1" \
-d parse_mode="HTML"
}
check_sys_util() {
mem_util=$(mem_util)
if [[ mem_util -gt $MEM_THRESHOLD ]]; then
send_telegram_msg "High Memory Usage Alert: ${mem_util}%"
fi
cpu_util=$(cpu_util)
if [[ cpu_util -gt $CPU_THRESHOLD ]]; then
send_telegram_msg "High CPU Usage Alert: ${cpu_util}%"
fi
}
while true; do
check_sys_util
sleep $SAMPLE_RATE
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment