MST
星途 面试题库

面试题:Bash脚本实现复杂监控系统中的动态阈值报警

设计一个Bash脚本用于监控服务器磁盘空间使用情况。要求当磁盘空间使用率超过70%时,通过邮件发送警告信息;当使用率低于30%时,发送恢复正常的邮件。并且脚本能够根据服务器配置动态调整这些阈值(通过配置文件读取阈值),配置文件格式为每行一个键值对,如 threshold_high=80 。
33.9万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试

以下是实现该功能的Bash脚本:

#!/bin/bash

# 读取配置文件
config_file="config.txt"
if [ -f "$config_file" ]; then
    source "$config_file"
else
    echo "配置文件 $config_file 不存在,使用默认阈值"
    threshold_high=70
    threshold_low=30
fi

# 获取磁盘空间使用率
usage=$(df -h | awk '$NF=="/"{print $(NF-1)}' | sed 's/%//')

# 判断磁盘空间使用率并发送邮件
if (( $(echo "$usage > $threshold_high" | bc -l) )); then
    echo "磁盘空间使用率超过 $threshold_high%,当前使用率为 $usage%" | mail -s "磁盘空间警告" your_email@example.com
elif (( $(echo "$usage < $threshold_low" | bc -l) )); then
    echo "磁盘空间使用率低于 $threshold_low%,当前使用率为 $usage%" | mail -s "磁盘空间恢复正常" your_email@example.com
fi

假设配置文件config.txt内容示例如下:

threshold_high=80
threshold_low=20

请将your_email@example.com替换为实际接收邮件的邮箱地址。同时确保服务器已配置好邮件发送功能(例如安装并配置mailutils等邮件客户端)。