Linux服务器超流量自动关机

很多服务商提供的服务器都有流量限制,为了避免流量超额,搞了个脚本。

安装依赖

vnstat 用于网卡流量统计,bc 用于后续脚本中的数字处理

sudo apt install vnstat bc -y

修改 vnstat 配置文件 /etc/vnstat.conf

# 选择网卡
Interface "enh0"

# 选择单位 (这项主要影响我们查看, 不影响脚本)
# 0 = IEC 标准前缀 (KiB/MiB/GiB...)
# 1 = 旧式二进制前缀 (KB/MB/GB...)
# 2 = SI 十进制前缀 (kB/MB/GB...)
# 0和1都是1024为基数,只是后缀单位不同;2以1000为基数。
UnitMode 0

# 每月重置日期
MonthRotate 1

重启 vnstat 服务: systemctl restart vnstat

使用 vnstat --help 查看 vnstat 基本用法

vnStat 2.10 by Teemu Toivola <tst at iki dot fi>

      -5,  --fiveminutes [limit]   show 5 minutes
      -h,  --hours [limit]         show hours
      -hg, --hoursgraph            show hours graph
      -d,  --days [limit]          show days
      -m,  --months [limit]        show months
      -y,  --years [limit]         show years
      -t,  --top [limit]           show top days

      -b, --begin <date>           set list begin date
      -e, --end <date>             set list end date

      --oneline [mode]             show simple parsable format
      --json [mode] [limit]        show database in json format
      --xml [mode] [limit]         show database in xml format
      --alert <output> <exit> <type> <condition> <limit> <unit>
                                   alert if limit is exceeded

      -tr, --traffic [time]        calculate traffic
      -l,  --live [mode]           show transfer rate in real time
      -i,  --iface <interface>     select interface

Use "--longhelp" or "man vnstat" for complete list of options.

编写脚本

#!/bin/bash

# 网卡名称
interface_name="eth0"

# 流量阈值上限 (GB)
traffic_limit=450

# 检查系统是否开机超过10分钟,如果未超过则退出脚本
# 避免重新启动后操作时间不足再次关机
uptime_minutes=$(cut -d. -f1 /proc/uptime)
if (( uptime_minutes < 600 )); then
    echo "System has not been running for at least 10 minutes. Exiting."
    exit 0
fi

# 显示当前用量
vnstat -i "$interface_name"

# $9进站, $10出站, $11进站出站之和
traffic_used=$(vnstat --oneline b -i "$interface_name" | awk -F';' '{print $11}')

# 确保 traffic_used 是数字
if ! [[ "$traffic_used" =~ ^[0-9]+$ ]]; then
    echo "Error: traffic_used is not a number."
    exit 1
fi

# 字节 换算为 GB (1GB = 1073741824 字节)
traffic_used=$(echo "scale=2; $traffic_used / 1073741824" | bc)

echo ""
echo "Used: $traffic_used GB"

# 比较是否超出限制
if (( $(echo "$traffic_used > $traffic_limit" | bc -l) )); then
    echo Excessive traffic, shutting down...
    shutdown -h now
else
    remaining_traffic=$(echo "scale=2; $traffic_limit - $traffic_used" | bc)
    echo "Remaining: $remaining_traffic GB"
fi

保存脚本,然后搞个定时任务,5分钟调用一次。

本文链接:

https://blog.nkxingxh.top/archives/419/
1 + 2 =
快来做第一个评论的人吧~