如何编写预算超限提醒脚本

wen 实用脚本 27

本文目录导读:

如何编写预算超限提醒脚本

  1. Shell 脚本方式(Linux/Unix)
  2. Python 脚本方式
  3. Excel VBA 宏方式
  4. 定期执行配置
  5. Docker 容器化部署
  6. 配置示例(config.yaml)
  7. 使用建议

Shell 脚本方式(Linux/Unix)

基础监控脚本

#!/bin/bash
# 预算限额
BUDGET_LIMIT=10000
# 获取当前已使用金额(示例:从日志文件读取)
CURRENT_SPEND=$(tail -1 /var/log/budget.log | awk '{print $2}')
# 比较并提醒
if [ "$CURRENT_SPEND" -gt "$BUDGET_LIMIT" ]; then
    echo "⚠️ 警告:预算已超限!"
    echo "当前支出:$CURRENT_SPEND"
    echo "预算限额:$BUDGET_LIMIT"
    # 发送邮件提醒
    echo "预算超限提醒" | mail -s "警告:预算超限" admin@example.com
    # 或发送webhook通知
    curl -X POST -H "Content-Type: application/json" \
         -d '{"text":"预算超限提醒"}' \
         https://hooks.example.com/webhook
fi

Python 脚本方式

功能完整的预算监控脚本

#!/usr/bin/env python3
import json
import smtplib
import requests
from datetime import datetime
import logging
class BudgetMonitor:
    def __init__(self, budget_limit, data_source):
        self.budget_limit = budget_limit
        self.data_source = data_source
    def get_current_spend(self):
        """获取当前支出"""
        # 从数据库或API获取
        try:
            with open(self.data_source, 'r') as f:
                data = json.load(f)
            return sum(data['expenses'])
        except Exception as e:
            logging.error(f"读取支出数据失败: {e}")
            return None
    def check_budget(self):
        """检查预算"""
        current_spend = self.get_current_spend()
        if current_spend is None:
            return
        usage_percentage = (current_spend / self.budget_limit) * 100
        # 分级预警
        if current_spend >= self.budget_limit:
            self.send_alert("严重", f"预算已超限!使用率: {usage_percentage:.2f}%")
        elif usage_percentage >= 90:
            self.send_alert("警告", f"预算即将超限!使用率: {usage_percentage:.2f}%")
        elif usage_percentage >= 80:
            self.send_alert("提醒", f"预算使用率已超过80%: {usage_percentage:.2f}%")
    def send_alert(self, level, message):
        """发送提醒"""
        alert_message = f"""
        [{datetime.now()}]
        级别: {level}
        消息: {message}
        """
        # 邮件提醒
        self.send_email(alert_message)
        # 钉钉/企业微信机器人
        self.send_webhook(alert_message)
        print(alert_message)
    def send_email(self, message):
        """发送邮件"""
        # 配置邮件服务器
        smtp_server = "smtp.gmail.com"
        smtp_port = 587
        sender = "monitor@example.com"
        password = "your_password"
        receiver = "admin@example.com"
        try:
            with smtplib.SMTP(smtp_server, smtp_port) as server:
                server.starttls()
                server.login(sender, password)
                server.send_message(sender, receiver, message)
        except Exception as e:
            logging.error(f"邮件发送失败: {e}")
    def send_webhook(self, message):
        """发送Webhook通知"""
        webhook_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx"
        try:
            response = requests.post(webhook_url, json={
                "msgtype": "text",
                "text": {"content": message}
            })
            response.raise_for_status()
        except Exception as e:
            logging.error(f"Webhook发送失败: {e}")
# 使用示例
if __name__ == "__main__":
    monitor = BudgetMonitor(
        budget_limit=100000, 
        data_source="/path/to/expenses.json"
    )
    monitor.check_budget()

Excel VBA 宏方式

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim budgetCell As Range
    Dim spentRange As Range
    Dim totalSpent As Double
    Dim budgetLimit As Double
    ' 设置单元格范围
    Set budgetCell = Range("B1")  ' 预算限额
    Set spentRange = Range("A2:A100")  ' 支出数据
    ' 计算总支出
    totalSpent = Application.WorksheetFunction.Sum(spentRange)
    budgetLimit = budgetCell.Value
    ' 检查是否超限
    If totalSpent > budgetLimit Then
        MsgBox "⚠️ 预算超限提醒!" & vbCrLf & _
               "当前支出: " & totalSpent & vbCrLf & _
               "预算限额: " & budgetLimit, _
               vbExclamation, "预算监控"
    End If
End Sub

定期执行配置

Crontab(Linux)

# 每5分钟检查一次
*/5 * * * * /path/to/budget_monitor.sh
# 每小时检查
0 * * * * /usr/bin/python3 /path/to/budget_monitor.py
# 每天9点检查
0 9 * * * /path/to/budget_monitor.sh

Windows 任务计划程序

schtasks /create /tn "BudgetMonitor" /tr "python C:\scripts\budget_monitor.py" /sc minute /mo 5

Docker 容器化部署

FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY budget_monitor.py .
COPY config.yaml .
CMD ["python", "budget_monitor.py"]

配置示例(config.yaml)

# 预算配置
budget:
  limit: 100000  # 预算限额
  warning_threshold: 80  # 预警阈值(百分比)
  critical_threshold: 90  # 严重预警阈值
# 数据源
data_source:
  type: database  # database, api, file
  connection: "mysql://user:pass@host/budget_db"
# 通知方式
notifications:
  email:
    enabled: true
    smtp_server: "smtp.gmail.com"
    smtp_port: 587
    recipients: ["admin@company.com"]
  webhook:
    enabled: true
    url: "https://hooks.example.com/alert"

使用建议

  • 分级预警:设置80%、90%、100%多级预警
  • 多通道通知:邮件、短信、即时通讯工具
  • 数据持久化:记录每次检查的结果
  • 错误处理:确保脚本健壮性
  • 性能优化:避免频繁查询数据库

选择哪种方式取决于你的技术栈和具体需求,需要更详细的实现说明吗?

抱歉,评论功能暂时关闭!