监测VPS流量使用量的脚本

1,399次阅读
没有评论

直接上代码,此脚本使用了 chatGPT 辅助编写。
可以设置成计划任务执行。
脚本需要调用 vnstat
保存为 .py 文件后,加执行权限后即可使用。
需要其他功能就自己改好了

#!/usr/bin/env python3
import smtplib
import subprocess
import ssl
import requests
from email.mime.text import MIMEText
from datetime import datetime, timedelta

# 流量限制,单位为 GB
LIMIT = 2000
BARK_URL = ‘https://’ # Bark 推送 URL
TELEGRAM_BOT_TOKEN = ‘122389:AAH8zMv’ # Telegram Bot Token
TELEGRAM_CHAT_ID = ‘8108’ # Telegram Chat ID

# 设置起始日期为每个月的固定日期
StartDate = 1

today = datetime.now()
if today.day >= StartDate:
start_date = datetime(today.year, today.month, StartDate)
else:
prev_month = today.month – 1 if today.month > 1 else 12
prev_year = today.year – 1 if prev_month == 12 else today.year
start_date = datetime(prev_year, prev_month, StartDate)

# 计算时间范围
end_date = datetime.now()

# 获取每天的流量并相加
total = 0
for i in range((end_date – start_date).days + 1):
date = start_date + timedelta(days=i)
cmd = f”vnstat -d -i eth0 | grep {date.strftime(‘%Y-%m-%d’)}”
result = subprocess.check_output(cmd, shell=True, universal_newlines=True)
data = result.strip().split(‘;’)
rx_unit = data[0].strip().split()[2]
rx = float(data[0].strip().split()[1])
tx_unit = data[0].strip().split()[5]
tx = float(data[0].strip().split()[4])
if rx_unit == “GiB”:
rx = rx * 1024
if tx_unit == “GiB”:
tx = tx * 1024
if rx_unit == “KiB”:
rx = rx / 1024
if tx_unit == “KiB”:
tx = tx / 1024
total += rx + tx

# 将总流量换算成 GB
if rx_unit == “MiB” and tx_unit == “MiB”:
total_gb = total / 1024
else:
total_gb = total / 1024 / 1024 / 1024

# 计算剩余流量和使用量百分比
traffic2 = LIMIT – total_gb
percentage = total_gb / LIMIT * 100
percentage2 = 100 – percentage

# 输出流量信息和百分比到屏幕
print(f”{start_date.strftime(‘%Y-%m-%d’)} 至 {end_date.strftime(‘%Y-%m-%d’)} \n 流量已使用: {total_gb:.2f} GB ({percentage:.2f}%) \n 剩余 {traffic2 :.2f} GB ({percentage2:.2f}%)”)

# 发送 Bark 推送
title = f” 流量使用统计 ”
body = f”{start_date.strftime(‘%Y-%m-%d’)} 至 {end_date.strftime(‘%Y-%m-%d’)} \n 流量已使用: {total_gb:.2f} GB ({percentage:.2f}%) \n 剩余 {traffic2 :.2f} GB ({percentage2:.2f}%)”
url = f”{BARK_URL}{title}/{body}”
requests.get(url)

# 发送 Telegram 推送
title = f”* 流量使用统计 *”
body = f”\n{start_date.strftime(‘%Y-%m-%d’)} 至 {end_date.strftime(‘%Y-%m-%d’)} \n 流量已使用: {total_gb:.2f} GB ({percentage:.2f}%) \n 剩余 {traffic2 :.2f} GB ({percentage2:.2f}%)”
url = f”https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage?chat_id={TELEGRAM_CHAT_ID}&text={title}{body}&parse_mode=markdown”
requests.get(url)

正文结束
 
欢迎加入 Telegram 群 https://t.me/Fit10086
文章教程好用记得留言支持啊
评论(没有评论)
载入中...