天天看點

linux腳本檢查cpu,Linux檢測CPU | 記憶體 | 磁盤使用率Shell腳本(釘釘通知)

#!/bin/bash

# BLOG : //renwole.com

now_time=$(date -u -d"+8 hour" +'%Y-%m-%d %H:%M:%S')

# 擷取域名

hostnamelist=$(hostname)

# 當cpu使用率大于設定的閥值觸發報警

cpu_warn="60"

# 當記憶體僅剩餘2048MB時觸發報警

mem_warn="2048"

# 當磁盤使用率大于設定的閥值觸發報警

disk_warn="80"

# 每執行一次都會在機器上生成對應的日志

renwole_check_log="/tmp/renwole_check_mem_cpu_disk.log"

# 釘釘報警Token

dingtalk_openapi="//oapi.dingtalk.com"

dingtalk_openapi_token="Token"

# 擷取CPU使用率

item_cpu () {

cpu_idle=$(top -b -n 1 | grep Cpu | awk '{print $2}' | cut -f 1 -d ".")

echo "$now 目前cpu使用率為 $cpu_idle" >> $renwole_check_log

if [[ "$cpu_idle" -gt "$cpu_warn" ]]; then

curl ''$dingtalk_openapi'/robot/send?access_token='$dingtalk_openapi_token'' \

-H 'Content-Type: application/json' \

-d '{"msgtype": "text",

"text": {

"content": "警告:目前機器'$hostnamelist'CPU使用率達到60%,請知曉."

}

}'

else

echo "CPU健康狀态正常"

fi

}

# 擷取記憶體消耗情況

item_mem () {

mem_free=$(free -m | grep "Mem" | awk '{print $4+$6}')

echo "$now 目前記憶體剩餘空間為 ${mem_free}MB" >> $renwole_check_log

if [[ "$mem_free" -lt "$mem_warn" ]]; then

curl ''$dingtalk_openapi'/robot/send?access_token='$dingtalk_openapi_token'' \

-H 'Content-Type: application/json' \

-d '{"msgtype": "text",

"text": {

"content": "警告:目前機器'$hostnamelist'記憶體使用率不足2048MB,請知曉."

}

}'

else

echo "記憶體使用率正常,放心使用"

fi

}

# 擷取磁盤使用情況

item_disk () {

disk_use=$(df -P | grep /dev/sdb1 | grep -v -E '(tmp|boot)' | awk '{print $5}' | cut -f 1 -d "%")

echo "$now 目前磁盤使用率為 $disk_use" >> $renwole_check_log

if [[ "$disk_use" -gt "$disk_warn" ]]; then

curl ''$dingtalk_openapi'/robot/send?access_token='$dingtalk_openapi_token'' \

-H 'Content-Type: application/json' \

-d '{"msgtype": "text",

"text": {

"content": "警告:目前機器'$hostnamelist'磁盤使用率達到80%,請知曉."

}

}'

else

echo "硬碟使用率未超過80%,放心使用"

fi

}

item_cpu

item_mem

item_disk