监控linux文件空间变化等小脚本

编写一个Shell脚本来监控文件目录的存在并进行相应的操作

#!/bin/bash

# 配置文件路径
config_file="directories.conf"

# 日志文件路径
log_file="monitor.log"

# 发送邮件的配置
recipient="your_email@example.com"
subject="目录监控报警"
from="monitor@example.com"

# 检查文件目录是否存在
check_directories() {
  while IFS= read -r directory; do
    if [ ! -d "$directory" ]; then
      echo "[$(date '+%Y-%m-%d %H:%M:%S')] 目录不存在: $directory" >> "$log_file"
      mkdir -p "$directory"
      echo "[$(date '+%Y-%m-%d %H:%M:%S')] 创建目录: $directory" >> "$log_file"
      send_email_notification "$directory"  # 发送邮件通知
    fi
  done < "$config_file"
}

# 发送邮件通知
send_email_notification() {
  local directory="$1"
  local message="目录不存在: $directory"

  echo "$message" | mail -s "$subject" -r "$from" "$recipient"
}

# 主循环
while true; do
  check_directories
  sleep 60  # 休眠一分钟后再次检查
done

目录配置文件 directories.conf:该文件包含要监控的目录路径,每行一个目录路径。
日志文件 monitor.log:用于记录操作日志,包括目录不存在和创建目录的记录。


用于监控一个文件夹中的文件,并在发现同一个文件长期存在时进行报警

#!/bin/bash

# 配置文件路径
config_file="monitor.conf"

# 日志文件路径
log_file="monitor.log"

# 读取配置文件
read_config() {
  if [ -f "$config_file" ]; then
    source "$config_file"
  else
    echo "配置文件不存在: $config_file"
    exit 1
  fi
}

# 检查文件是否超过阈值
check_files() {
  current_time=$(date +%s)
  for file in "${directories[@]}"; do
    if [ -f "$file" ]; then
      file_modified=$(stat -c "%Y" "$file")
      time_diff=$((current_time - file_modified))
      if [ "$time_diff" -gt "$threshold" ]; then
        echo "[$(date '+%Y-%m-%d %H:%M:%S')] 文件超时: $file" >> "$log_file"
        send_alarm_notification "$file"  # 发送报警通知
      fi
    fi
  done
}

# 发送报警通知
send_alarm_notification() {
  local file="$1"
  local message="文件超时: $file"

  # 在此处添加发送报警邮件或其他报警机制的代码
  # 例如,使用邮件客户端发送邮件
  echo "$message" | mail -s "文件超时报警" "$recipient"

  echo "$message"
}

# 主函数
main() {
  read_config
  check_files
}

# 执行主函数
main

配置文件 monitor.conf:该文件包含要监控的文件路径、报警阈值(以秒为单位)和报警机制的配置。例如:

# monitor.conf

directories=(
  "/path/to/directory/file.txt"
)
threshold=3600  # 1小时
recipient="your_email@example.com"

日志文件 monitor.log:用于记录操作日志,包括文件超时的记录。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值