Skip to content

Instantly share code, notes, and snippets.

@killbus
Last active February 23, 2025 17:56
Show Gist options
  • Select an option

  • Save killbus/503b0b42877e773d3c801f62e1771598 to your computer and use it in GitHub Desktop.

Select an option

Save killbus/503b0b42877e773d3c801f62e1771598 to your computer and use it in GitHub Desktop.

iptables_quota.sh

#!/bin/bash

# 脚本功能: 配置 iptables 流量配额控制
# 用法: sudo ./quota_control.sh

set -euo pipefail

# 配置
readonly INTERFACE="eth0+"      # 要监控的网络接口
readonly QUOTA_CHAIN="quota33g" # 自定义链名称
readonly QUOTA_LIMIT_BYTES="35433480192"  # 配额限制(字节), 约 33GB

# IP 配置
readonly BYPASS_IPS=(
    "192.168.1.100/32"
    "8.8.8.8/32"
)

readonly LAN_IPS=(
    "192.168.0.0/16"
    "10.0.0.0/8"
    "172.16.0.0/12"
)

# 日志函数
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

# 权限检查
[[ $EUID -eq 0 ]] || { echo "请使用 root 权限运行此脚本"; exit 1; }

# 配置防火墙规则
log "开始配置流量配额控制..."

# 确保链存在
if iptables -L "$QUOTA_CHAIN" 2>/dev/null; then
    # 如果链已存在,先移除 OUTPUT 中的引用,再清空链
    iptables -D OUTPUT -o "$INTERFACE" -j "$QUOTA_CHAIN" 2>/dev/null || true
    iptables -F "$QUOTA_CHAIN"
else
    # 创建新链
    iptables -N "$QUOTA_CHAIN"
fi

# 添加局域网规则
log "添加局域网规则..."
if (( ${#LAN_IPS[@]} > 0 )); then
    for lan_ip in "${LAN_IPS[@]}"; do
        iptables -A "$QUOTA_CHAIN" -d "$lan_ip" -j ACCEPT
    done
fi

# 添加白名单规则
if (( ${#BYPASS_IPS[@]} > 0 )); then
    for bypass_ip in "${BYPASS_IPS[@]}"; do
        iptables -A "$QUOTA_CHAIN" -d "$bypass_ip" -j ACCEPT
    done
fi

# 添加配额规则
log "添加配额控制规则..."
iptables -A "$QUOTA_CHAIN" -m quota --quota "$QUOTA_LIMIT_BYTES" -j RETURN

# 添加默认拒绝规则
iptables -A "$QUOTA_CHAIN" -j DROP

# 添加到 OUTPUT 链
log "添加到 OUTPUT 链..."
# 检查规则是否已存在
if ! iptables -C OUTPUT -o "$INTERFACE" -j "$QUOTA_CHAIN" 2>/dev/null; then
    iptables -A OUTPUT -o "$INTERFACE" -j "$QUOTA_CHAIN"
    log "规则已添加到 OUTPUT 链"
else
    log "规则已存在于 OUTPUT 链中,跳过添加"
fi

log "配置完成"

crontab

0 0 * * * /sbin/iptables -Z quota33g
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment