如何编写分配网络流量比例脚本

wen 实用脚本 25

本文目录导读:

如何编写分配网络流量比例脚本

  1. 使用iptables的statistic模块(适合单机)
  2. Python版本(更灵活)
  3. HAProxy方案(适合负载均衡)
  4. 实时监控脚本
  5. Docker容器流量分配
  6. 使用建议

我来介绍几种编写网络流量比例分配脚本的方法,主要使用Linux下的工具:

使用iptables的statistic模块(适合单机)

#!/bin/bash
# 流量比例分配脚本 - 使用iptables
# 70%流量走eth0,30%流量走eth1
# 清除旧规则
iptables -F -t mangle
iptables -X -t mangle
# 设置默认路由
ip route add default nexthop via 192.168.1.1 dev eth0 weight 7 \
                     nexthop via 192.168.2.1 dev eth1 weight 3
# 使用statistic模块按比例标记
iptables -t mangle -A PREROUTING -j CONNMARK --restore-mark
iptables -t mangle -A PREROUTING -m statistic --mode random --probability 0.7 -j MARK --set-mark 1
iptables -t mangle -A PREROUTING -j MARK --set-mark 2
iptables -t mangle -A PREROUTING -j CONNMARK --save-mark
# 根据标记路由
ip rule add fwmark 1 table 100
ip rule add fwmark 2 table 200
# 配置路由表
ip route add default via 192.168.1.1 dev eth0 table 100
ip route add default via 192.168.2.1 dev eth1 table 200

Python版本(更灵活)

#!/usr/bin/env python3
"""
网络流量比例分配脚本
"""
import random
import subprocess
import sys
class TrafficBalancer:
    def __init__(self, interfaces: dict):
        """
        :param interfaces: {'eth0': 0.7, 'eth1': 0.3}
        """
        self.interfaces = interfaces
    def get_next_interface(self) -> str:
        """基于权重随机选择接口"""
        rand = random.random()
        cumulative = 0
        for interface, weight in self.interfaces.items():
            cumulative += weight
            if rand <= cumulative:
                return interface
        return list(self.interfaces.keys())[-1]
    def route_packet(self, interface: str, gateways: dict):
        """路由数据包到指定接口"""
        gateway = gateways[interface]
        cmd = f"ip route add default via {gateway} dev {interface}"
        subprocess.run(cmd.split(), check=True)
# 使用示例
if __name__ == "__main__":
    # 配置接口和权重
    interfaces = {
        'eth0': 0.7,  # 70%流量
        'eth1': 0.3   # 30%流量
    }
    gateways = {
        'eth0': '192.168.1.1',
        'eth1': '192.168.2.1'
    }
    balancer = TrafficBalancer(interfaces)
    # 处理数据包
    interface = balancer.get_next_interface()
    balancer.route_packet(interface, gateways)

HAProxy方案(适合负载均衡)

# haproxy.cfg
global
    daemon
    maxconn 256
defaults
    mode tcp
    timeout connect 5000ms
    timeout client 50000ms
    timeout server 50000ms
frontend main
    bind *:80
    default_backend servers
backend servers
    balance roundrobin
    server server1 192.168.1.1:80 weight 7 maxconn 100
    server server2 192.168.2.1:80 weight 3 maxconn 100

实时监控脚本

#!/bin/bash
# 动态调整流量比例的监控脚本
# 配置
INTERFACE1="eth0"
INTERFACE2="eth1"
TARGET_RATIO=0.7  # 目标比例
monitor_traffic() {
    while true; do
        # 获取当前流量
        RX1=$(cat /sys/class/net/$INTERFACE1/statistics/rx_bytes)
        RX2=$(cat /sys/class/net/$INTERFACE2/statistics/rx_bytes)
        sleep 1
        RX1_END=$(cat /sys/class/net/$INTERFACE1/statistics/rx_bytes)
        RX2_END=$(cat /sys/class/net/$INTERFACE2/statistics/rx_bytes)
        # 计算速率
        RATE1=$(( (RX1_END - RX1) ))
        RATE2=$(( (RX2_END - RX2) ))
        if [ $RATE1 -gt 0 ] || [ $RATE2 -gt 0 ]; then
            RATIO=$(echo "scale=2; $RATE1 / ($RATE1 + $RATE2)" | bc)
            # 调整权重
            DIFF=$(echo "scale=2; $TARGET_RATIO - $RATIO" | bc)
            if [ $(echo "$DIFF > 0.1" | bc) -eq 1 ]; then
                echo "调整权重以匹配目标比例"
                adjust_weights
            fi
        fi
        sleep 5
    done
}
adjust_weights() {
    # 这里实现权重调整逻辑
    iptables -t mangle -F PREROUTING
    # 重新设置规则...
}
monitor_traffic

Docker容器流量分配

# docker-compose.yml
version: '3'
services:
  app1:
    image: nginx
    ports:
      - "80"
    deploy:
      resources:
        limits:
          cpus: '0.7'  # 70% CPU
          memory: 700M
  app2:
    image: nginx
    ports:
      - "80"
    deploy:
      resources:
        limits:
          cpus: '0.3'  # 30% CPU
          memory: 300M

使用建议

  1. 选择合适的方案

    • 单机多接口:使用iptables
    • 服务端负载均衡:使用HAProxy/Nginx
    • 需要动态调整:使用Python脚本
  2. 注意事项

    • 确保接口已正确配置IP和路由
    • 考虑连接状态(保持相同连接走相同路径)
    • 添加错误处理和日志记录
  3. 测试验证

    # 测试流量分配
    iperf -c 目标IP -P 10  # 多线程测试
    # 查看当前连接状态
    conntrack -L | grep 目标IP

需要更具体的实现吗?我可以根据你的使用场景提供更详细的配置。

抱歉,评论功能暂时关闭!