第一步,获取网卡流量信息
cat /sys/class/net/[网卡名称]/statistics/rx_bytes
cat /sys/class/net/[网卡名称]/statistics/tx_bytes
第二步,记录到sqlite3数据库
新建SQLITE表
CREATE TABLE network_hisroty( id INTEGER PRIMARY KEY, rx_bytes INTEGER, tx_bytes INTERGER, update_time TEXT DEFAULT datetime('now', '+8 hours'), total INTEGER GENERATED ALWAYS AS (tx_bytes + rx_bytes ) VIRTUAL);
插入数据
#!/bin/bash DB_FILE="/root/network_hisroty/network_hisroty.db3" rx=$(cat /sys/class/net/ens5/statistics/rx_bytes) tx=$(cat /sys/class/net/ens5/statistics/tx_bytes) sqlite3 "$DB_FILE" <<EOF INSERT INTO network_hisroty (rx_bytes,tx_bytes,update_time) VALUES ("$rx","$tx",datetime("now","+8 hours")); EOF
第三步,进行流量检查,达标后断流
#!/bin/bash
# 进入工作目录
cd /root/network_hisroty || { echo "Failed to cd to /root/network_hisroty"; exit 1; }
# 获取本月起始时间(格式:YYYY-MM-01 01:01:)
ds=$(date "+%Y-%m-01 01:01:")
# 获取当前时间(格式:YYYY-MM-%d %H:%M:)
dn=$(date "+%Y-%m-%d %H:%M:")
# 查询本月起始时间的 total 值
total_start=$(sqlite3 network_hisroty.db3 <<EOF
SELECT total FROM network_hisroty WHERE update_time LIKE '$ds%';
EOF)
# 查询当前时间的 total 值
total_now=$(sqlite3 network_hisroty.db3 <<EOF
SELECT total FROM network_hisroty WHERE update_time LIKE '$dn%';
EOF)
# 检查查询结果是否为空
if [ -z "$total_start" ]; then
echo "Error: No record found for start time '$ds'"
exit 1
fi
if [ -z "$total_now" ]; then
echo "Error: No record found for current time '$dn'"
exit 1
fi
# 输出结果
echo "Start total: $total_start"
echo "Current total: $total_now"