定期监控磁盘使用率

BBigSun 评论338阅读模式

由于 ELK 的日志较多,机器磁盘使用率超过 90% 后,ELK 就无法写入日志了。
写个脚本,监控一下,磁盘使用率超过 80%,发送通知到企微机器人。

1、通过命令行取到磁盘使用率

查看日志所在磁盘,以及使用率:文章源自十年又十年-https://www.bbigsun.com/76.html

$ df -h
Filesystem               Size  Used Avail Use% Mounted on
/dev/mapper/centos-root  291G  167G  125G  58% /
devtmpfs                 7.8G     0  7.8G   0% /dev
tmpfs                    7.8G     0  7.8G   0% /dev/shm
tmpfs                    7.8G   33M  7.8G   1% /run
tmpfs                    7.8G     0  7.8G   0% /sys/fs/cgroup
/dev/sda1               1014M  142M  873M  14% /boot
tmpfs                    1.6G     0  1.6G   0% /run/user/0

我这里是在 /dev/mapper/centos-root 下面,所以通过 grep centos-root 来过滤:文章源自十年又十年-https://www.bbigsun.com/76.html

$ df -h | grep centos-root
/dev/mapper/centos-root  291G  167G  125G  58% /

接着通过 awk '{print $5}' 取到磁盘使用率:文章源自十年又十年-https://www.bbigsun.com/76.html

$ df -h | grep centos-root | awk '{print $5}'
58%

因为要做比较,所以去掉 %:文章源自十年又十年-https://www.bbigsun.com/76.html

$ df -h | grep centos-root | awk '{print $5}' | xargs | sed s/%//
58

2、企微通知的两种写法

在 Linux 上可以使用 curl 命名发送请求。(要确保这台机器防火墙没有禁止,如果 curl 命令无法发送请求的话,大概率是网络问题)文章源自十年又十年-https://www.bbigsun.com/76.html

第一种:(写很多行)写成多行时,注意加 \ 进行换行文章源自十年又十年-https://www.bbigsun.com/76.html

curl 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=693axxx6-7aoc-4bc4-97a0-0ec2sifa5aaa' \
    -H 'Content-Type: application/json' \
    -d '
    {
        "msgtype": "text",
        "text": {
            "content": "磁盘要满了,ELK要罢工了"
        }
    }'

第二种:(写成一行)写成一行时,注意对 " 进行转义文章源自十年又十年-https://www.bbigsun.com/76.html

curl -H 'Content-Type: application/json;charset=utf-8'  -d '{\"msgtype\": \"text\",\"text\": {\"content\":\"磁盘要满了,ELK要罢工了\"}}' 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=693axxx6-7aoc-4bc4-97a0-0ec2sifa5aaa'

3、源码

#!/bin/bash

# 监控该机器磁盘使用率,超过80%,发送警告到企业微信

use=df -h | grep centos-root | awk '{print $5}' | xargs | sed s/%//
if [ $use -ge 80 ];then
    echo $use
    curl 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=693axxx6-7aoc-4bc4-97a0-0ec2sifa5aaa' \
    -H 'Content-Type: application/json' \
    -d '
    {
        "msgtype": "text",
        "text": {
            "content": "磁盘要满了,ELK要罢工了"
        }
    }'
fi
文章源自十年又十年-https://www.bbigsun.com/76.html文章源自十年又十年-https://www.bbigsun.com/76.html

纸上得来终觉浅,绝知此事要躬行。

weinxin
17688689121
我的微信
微信扫一扫
BBigSun
  • 本文由 BBigSun 发表于 2022年 11月 24日 09:54:24
  • 转载请务必保留本文链接:https://www.bbigsun.com/76.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定