|
发表于 2024-9-9 00:21:17
|
显示全部楼层
试试用vnstat的月度流量统计功能,能取到网卡月度的tx值,还在测试脚本统计到的和阿里云后台的差多少。阿里云统计的应该是CDT的流出流量。
先安装vnstat
apt install vnstat
激活eth0的vnstat统计
vnstat -i eth0
systemctl restart vnstat
systemctl enable vnstat
脚本如下,先保存脚本到某路径下的文件。
#!/bin/bash
# 设置网卡接口名称
INTERFACE="eth0"
# 设置流量上限(以MB为单位,这里是18000MB,即18GB)
LIMIT=18000 # 18GB in MB
# 设置日志文件路径
LOG_FILE="/var/log/traffic_monitor.log"
# 获取当前时间
CURRENT_TIME=$(date "+%Y-%m-%d %H:%M:%S")
# 从vnstat获取当前月度的流出流量(单位为MB)
current_tx=$(vnstat --oneline -i $INTERFACE -m | grep "`date +'%Y-%m'`" | awk -F "|" '{print $2}' | awk '{print $1 $2}')
# 将流出流量转换为MB单位
if [[ $current_tx == *"KiB"* ]]; then
current_tx=$(echo "$current_tx" | awk '{print int($1 / 1024)}')
elif [[ $current_tx == *"MiB"* ]]; then
current_tx=$(echo "$current_tx" | awk '{print int($1)}')
elif [[ $current_tx == *"GiB"* ]]; then
current_tx=$(echo "$current_tx" | awk '{print int($1 * 1024)}')
fi
# 写入日志并检查流量限制
if [ "$current_tx" -ge "$LIMIT" ]; then
echo "$CURRENT_TIME - Monthly outgoing traffic limit reached: ${current_tx}MB. Shutting down..." >> "$LOG_FILE"
sudo shutdown -h now
else
echo "$CURRENT_TIME - Current outgoing traffic this month: ${current_tx}MB, Limit: ${LIMIT}MB" >> "$LOG_FILE"
fi
然后设置crontab定时每5分钟执行一次和每天凌晨3点清空日志文件。
crontab -e
*/5 * * * * /path/to/your/script.sh
0 3 * * * > /var/log/traffic_monitor.log
|
|