CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-v2ray-util

V2ray/Xray multi-user management utility for configuring proxy servers with various transport protocols

Overview
Eval results
Files

traffic-statistics.mddocs/

Traffic Statistics

Comprehensive traffic monitoring and statistics collection for V2ray/Xray proxy servers. Provides traffic analysis through both V2ray's official API and iptables-based monitoring, enabling detailed usage tracking and bandwidth management.

Capabilities

V2ray API Statistics

Traffic statistics collection using V2ray's built-in statistics API for accurate per-user and per-group monitoring.

class StatsFactory:
    """V2ray statistics API management"""
    
    def __init__(self, group_list):
        """
        Initialize statistics factory with group configuration.
        
        Parameters:
        - group_list (list): List of configured port groups
        """
    
    def get_stats(self, group_list):
        """
        Retrieve comprehensive traffic statistics for all groups.
        
        Parameters:
        - group_list (list): Groups to collect stats for
        
        Returns:
        dict: Traffic statistics including uplink/downlink bytes
              for each user and group
        """
    
    def get_inbound_stats(self, group_list):
        """
        Get inbound traffic statistics specifically.
        
        Parameters:
        - group_list (list): Target groups
        
        Returns:
        dict: Inbound traffic data per user/group
        """

def manage(stat_type=''):
    """
    Interactive traffic statistics management.
    
    Parameters:
    - stat_type (str, optional): Specific statistics type to display
                                'user' - Per-user statistics
                                'group' - Per-group statistics
                                'total' - Overall statistics
    
    Provides interactive menu for viewing and managing traffic statistics,
    including options to reset counters and export data.
    """

Iptables-based Statistics

Alternative traffic monitoring using iptables rules for system-level traffic analysis.

def manage(iptables_type=''):
    """
    Manage iptables-based traffic statistics.
    
    Parameters:
    - iptables_type (str, optional): Statistics type
                                    'port' - Per-port statistics
                                    'user' - Per-user via port mapping
                                    'total' - System-wide proxy traffic
    
    Provides iptables rule management and traffic data collection
    independent of V2ray's API statistics.
    """

def calcul_iptables_traffic(port, ipv6=False):
    """
    Calculate traffic statistics for specific port using iptables.
    
    Parameters:
    - port (int): Port number to analyze
    - ipv6 (bool): Include IPv6 traffic statistics
    
    Returns:
    tuple: (upload_bytes, download_bytes) for the specified port
    """

def clean_iptables(port):
    """
    Clean iptables rules and reset statistics for specific port.
    
    Parameters:
    - port (int): Port to clean rules for
    
    Removes monitoring rules and resets byte counters.
    """

Statistics Data Management

class Stats:
    """Traffic statistics data management"""
    
    def __init__(self):
        """Initialize statistics manager"""
    
    def reset_stats(self):
        """Reset all traffic statistics counters"""
    
    def export_stats(self, format='json'):
        """
        Export statistics data.
        
        Parameters:
        - format (str): Export format ('json', 'csv', 'txt')
        
        Returns:
        str: Formatted statistics data
        """

Usage Examples

V2ray API Statistics

from v2ray_util.global_setting.stats_ctr import manage, StatsFactory
from v2ray_util.util_core.profile import Profile

# Interactive statistics management
manage()

# Programmatic statistics collection
profile = Profile()
groups = profile.load()
stats = StatsFactory(groups)

# Get all traffic statistics
all_stats = stats.get_stats(groups)
print(f"Total traffic: {all_stats}")

# Get inbound statistics only
inbound_stats = stats.get_inbound_stats(groups)

Iptables Statistics

from v2ray_util.global_setting.iptables_ctr import manage
from v2ray_util.util_core.utils import calcul_iptables_traffic, clean_iptables

# Interactive iptables management
manage()

# Get traffic for specific port
upload, download = calcul_iptables_traffic(8080)
print(f"Port 8080 - Upload: {upload}, Download: {download}")

# Include IPv6 traffic
upload, download = calcul_iptables_traffic(8080, ipv6=True)

# Clean statistics for port
clean_iptables(8080)

Command Line Statistics

# V2ray API statistics
v2ray-util stats           # Interactive statistics menu
v2ray-util stats user      # Per-user statistics
v2ray-util stats total     # Total statistics

# Iptables statistics  
v2ray-util iptables        # Interactive iptables menu
v2ray-util iptables port   # Per-port statistics

Statistics Data Format

V2ray API Statistics Structure

StatsData = {
    "groups": [
        {
            "port": int,
            "protocol": str,
            "users": [
                {
                    "email": str,
                    "uplink": int,      # Bytes sent
                    "downlink": int,    # Bytes received
                    "total": int        # Total bytes
                }
            ],
            "group_total": {
                "uplink": int,
                "downlink": int,
                "total": int
            }
        }
    ],
    "system_total": {
        "uplink": int,
        "downlink": int,
        "total": int,
        "active_users": int,
        "active_groups": int
    }
}

Iptables Statistics Structure

IptablesData = {
    "ports": {
        "8080": {
            "input_bytes": int,
            "output_bytes": int,
            "input_packets": int,
            "output_packets": int
        }
    },
    "total": {
        "input_bytes": int,
        "output_bytes": int,
        "input_packets": int,
        "output_packets": int
    }
}

Traffic Analysis Features

Real-time Monitoring

  • Live traffic statistics display
  • Automatic refresh intervals
  • Color-coded output for different traffic levels

Historical Data

  • Traffic history tracking
  • Daily, weekly, monthly summaries
  • Data export capabilities

User Analytics

  • Per-user bandwidth usage
  • Top users by traffic volume
  • Usage pattern analysis

Alert System

  • Bandwidth threshold alerts
  • Unusual traffic pattern detection
  • User quota management

Utility Functions

Data Formatting

def bytes_2_human_readable(number_of_bytes, precision=1):
    """
    Convert bytes to human-readable format.
    
    Parameters:
    - number_of_bytes (int): Raw byte count
    - precision (int): Decimal precision for display
    
    Returns:
    str: Formatted string (e.g., "1.5 GB", "256.7 MB")
    """

Port Management

def all_port():
    """
    Get list of all configured ports with statistics.
    
    Returns:
    list: Port numbers with associated traffic data
    """

Integration with Global Settings

Traffic statistics integrate with other global settings:

Bandwidth Limiting

  • Per-user bandwidth caps
  • Group-level traffic limits
  • Dynamic throttling based on usage

Automated Management

  • Automatic user cleanup based on inactivity
  • Traffic-based user tier management
  • Cost tracking and billing integration

Monitoring Integration

  • Log correlation with traffic patterns
  • Performance metrics collection
  • System resource usage tracking

Data Persistence

Statistics data is persisted through:

  • JSON configuration files
  • SQLite databases for historical data
  • Log file integration for audit trails
  • Export capabilities for external analysis tools

Install with Tessl CLI

npx tessl i tessl/pypi-v2ray-util

docs

config-modification.md

core-management.md

index.md

traffic-statistics.md

user-port-management.md

utilities-global-settings.md

tile.json