需求
最近需要給自己的伺服器新增監控器,目的是監控伺服器的記憶體、CPU、磁碟佔用率,資源佔用率過高的話能給自己發個提醒,當前主流的平臺一般會提供郵件、短息、甚至會提供微信提醒,不過這類提醒包含的噪音太多了(夾雜著各種無關的社交資訊),我只是單純的需要接收到伺服器的預警。由於伺服器環境並不複雜,所以不考慮主流的與監控平臺(畢竟搭建起來還是挺複雜的)。
選擇產品
有很多產品支援 incoming(就是通過呼叫應用提供的 API 把我們自定義的訊息轉傳送該應用),我打算使用 JBox ,因為它提供了 Android、和 iOS 客戶端支援而且是開源的所以後期有什麼需求都可以自己加上去(還有一點最主要的是使用起來非常簡單,API 文件只有一個介面,基本沒有學習成本)。
著手操作
按照 JBox 教程 來,首先新建一個自定義整合,獲得一個 Webhook url
http://jbox.jiguang.cn/v1/message/dxwYTMfrC8GRhU5/vwlrqCegmp //注意:這裡填寫自己整合的 Webhook url,每個整合的 Webhook 都不一樣。複製程式碼
首先編寫我們的監控指令碼,這裡我寫了兩個指令碼
#記憶體監控指令碼 monitor_memory.sh
webhook="http://jbox.jiguang.cn:80/v1/message/dxwYTMfrC8GRhU5/vwlrqCegmp" #注意:這裡填寫自己整合的 Webhook url
#告警閾值30G,少於則告警,頻率 30分鐘 檢查一次
normal=30
#取得總記憶體
#取得記憶體分頁數
freemk=`vmstat 5 2 | tail -n 1 | awk '{print $5}'`;
#每一頁是4K ,所以乘以4
freemm=`expr $freemk \* 4`;
#轉換為 G
freemem=`echo $freemm/1024/1024|bc`;
echo `date +%Y%m%d%H%M`" Memory:" "M" all $freemem"G" avail;
if [ $freemem -lt $normal ]
then
echo "當前記憶體"$freemem"G,少於"$normal"G" #列印告警資訊 這裡可以插入簡訊庫,傳送至手機
title="記憶體告警!!"
message="當前記憶體"$freemem"G,少於"$normal"G"
memoryAlertJson='{"title":"'${title}'"'',"message":"'${message}'"}'
echo $memoryAlertJson
# 這裡傳送預警,該條訊息會轉發到 JBOx app
curl -H "Content-Type: application/json" -X POST -d $memoryAlertJson $webhook
fi複製程式碼
# 磁碟監控指令碼 monitor_disk.sh
webhook="http://jbox.jiguang.cn:80/v1/message/dxwYTMfrC8GRhU5/vwlrqCegmp"
normal=10 #當超過 10% 這個值時產生告警,這裡因為測試 所以設得很低,這個可以根據自己的需求來增加
DiskPercent=`df |grep -w / |awk '{print $5}'|awk -F '%' '{print $1}'`;
echo $DiskPercent;
if [ $normal -lt $DiskPercent ]
then
echo "硬碟 使用率告警"
title="硬碟 使用率告警!!"
message="當前使用率"$DiskPercent"%,大於"$normal"%"
DiskAlertJson='{"title":"'${title}'"'',"message":"'${message}'"}'
echo $DiskAlertJson
# 這裡傳送預警,該條訊息會轉發到 JBOx app
curl -H "Content-Type: application/json" -X POST -d $DiskAlertJson $webhook
fi複製程式碼
我把這兩個指令碼加在 crontab 執行計劃裡面
$ crontab -e
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
# 一分鐘執行一次指令碼
* * * * * /bin/bash /home/ubuntu/monitor_memory.sh >>/home/ubuntu/moniter_memory.log
* * * * * /bin/bash /home/ubuntu/monitor_disk.sh >>/home/ubuntu/monitor_disk.log複製程式碼