# 函数:发送通知 send_notification() { local title="$1" local message="$2" curl -X POST -d """$NOTIFICATION_URL/$title/$message" > /dev/null 2>&1 echo"$(date +%Y-%m-%d_%H:%M:%S) 已发送通知: $title - $message" >> $LOG_FILE }
# 函数:替换消息中的占位符 replace_placeholders() { local message="$1" local usage="$2" locallimit="$3" local percent="$4" local action="$5" message="${message//\{USAGE\}/$usage}" message="${message//\{LIMIT\}/$limit}" message="${message//\{PERCENT\}/$percent}" message="${message//\{ACTION\}/$action}" echo"$message" }
# 初始化状态 if [ -f "$STATE_FILE" ]; then source$STATE_FILE else BLOCKED=false WARNED=false echo"BLOCKED=false" > $STATE_FILE echo"WARNED=false" >> $STATE_FILE fi
# 检查是否需要发出警告 WARNING_LIMIT=$(echo"$MONTHLY_LIMIT_GB * $WARNING_THRESHOLD" | bc) if (( $(echo "$MONTHLY_USAGE >= $WARNING_LIMIT" | bc -l) )) && ! $WARNED; then USAGE_PERCENT=$(echo"scale=1; $MONTHLY_USAGE / $MONTHLY_LIMIT_GB * 100" | bc) WARNING_MSG=$(replace_placeholders "$WARNING_MESSAGE""$MONTHLY_USAGE""$MONTHLY_LIMIT_GB""$USAGE_PERCENT""") send_notification "$NOTIFICATION_TITLE""$WARNING_MSG" WARNED=true echo"WARNED=true" >> $STATE_FILE fi
# 检查是否需要采取行动 if (( $(echo "$MONTHLY_USAGE >= $MONTHLY_LIMIT_GB" | bc -l) )) && ! $BLOCKED; then if [ "$ACTION_ON_LIMIT" = "DROP" ]; then block_network ACTION_MSG="网络已被封锁" elif [ "$ACTION_ON_LIMIT" = "SHUTDOWN" ]; then ACTION_MSG="系统即将关机" fi LIMIT_MSG=$(replace_placeholders "$LIMIT_REACHED_MESSAGE""$MONTHLY_USAGE""$MONTHLY_LIMIT_GB""100""$ACTION_MSG") send_notification "$NOTIFICATION_TITLE""$LIMIT_MSG" if [ "$ACTION_ON_LIMIT" = "SHUTDOWN" ]; then shutdown_system fi fi
# 每月 1 号 0 点重置状态 if [[ "$(date +%d)" == "01" ]] && [[ "$(date +%H:%M)" == "00:00" ]]; then if$BLOCKED; then unblock_network send_notification "$NOTIFICATION_TITLE""$RESET_MESSAGE" fi WARNED=false echo"WARNED=false" > $STATE_FILE fi done