2022年7月

xray是一个非常优秀的网络联通框架,很多科学爱好者都在使用~~~

xray集成了流量统计功能,但是通过api查询输出的结果为json格式,且结果单位为字节数。大概是为了方便别的程序使用,但是却不利用人眼直接查看。

为了方便查看流量统计结果,就用python写了一个脚本,格式化输出结果。
至于如何打开xray的流量统计功能,可以参考官方文档的描述,这里不做赘述。
脚本具体内容如下,可以保存成文件traffic.py,并加上可执行权限chmod +x traffic.py,就可以直接运行。
其中toolserver根据实际情况修改。

#!/usr/bin/python3

import json
import subprocess
import sys

tool = "/usr/local/bin/xray"
server = "127.0.0.1:8080"

result = {"inbound": {}, "outbound": {}, "user": {}}


def get_data():
    arg = ""
    if len(sys.argv) > 1 and sys.argv[1] == "reset":
        arg = "-reset"
    return subprocess.check_output(
        ([tool, "api", "statsquery", "--server=%s" % server, arg])).decode("utf-8")


def numfmt(num: int):
    if num >= 1024*1024*1024*1024:
        return "%.2fTB" % (num / 1024/1024/1024/1024)
    elif num >= 1024*1024*1024:
        return "%.2fGB" % (num / 1024/1024/1024)
    elif num >= 1024*1024:
        return "%.2fMB" % (num / 1024/1024)
    elif num >= 1024:
        return "%.2fKB" % (num / 1024)
    else:
        return "%.0fB" % num


def print_result(bound):
    data = result[bound]
    up = down = 0
    for key in sorted(data.keys(), reverse=True):
        if key.find("up") != -1:
            up += data[key]
        else:
            down += data[key]
        print("%-25s %9s" % (key, numfmt(data[key])))
    print("%-25s %9s" % ("SUM->up", numfmt(up)))
    print("%-25s %9s" % ("SUM->down", numfmt(down)))
    print("%-25s %9s" % ("SUM->TOTAL", numfmt(up+down)))


if __name__ == "__main__":
    for it in json.loads(get_data())["stat"]:
        key = it["name"].split(">>>")
        result[key[0]][key[1]+'->' +
                       key[3].replace("link", "")] = int(it.get("value", "0"))

    print("---------------Inbound-------------")
    print_result("inbound")
    print("---------------Inbound-------------\n")
    print("---------------Outbound-------------")
    print_result("outbound")
    print("---------------Outbound-------------\n")
    print("----------------User---------------")
    print_result("user")
    print("----------------User---------------")

原本的输出:

{
    "stat": [
        {
            "name": "outbound>>>direct>>>traffic>>>downlink",
            "value": 4257067673
        },
        {
            "name": "user>>>alundra>>>traffic>>>uplink",
            "value": 23392201
        },
        {
            "name": "user>>>alundra>>>traffic>>>downlink",
            "value": 3231432347
        },
        {
            "name": "user>>>winger>>>traffic>>>uplink",
            "value": 8298513
        },
        {
            "name": "user>>>winger>>>traffic>>>downlink",
            "value": 1025635326
        },
        {
            "name": "inbound>>>api>>>traffic>>>uplink",
            "value": 8653
        },
        {
            "name": "inbound>>>api>>>traffic>>>downlink",
            "value": 19613
        },
        {
            "name": "outbound>>>direct>>>traffic>>>uplink",
            "value": 31690208
        }
    ]
}

脚本运行的效果:

---------------Inbound-------------
api->up                      8.62KB
api->down                   19.61KB
SUM->up                      8.62KB
SUM->down                   19.61KB
SUM->TOTAL                  28.23KB
---------------Inbound-------------

---------------Outbound-------------
direct->up                  30.22MB
direct->down                 3.96GB
SUM->up                     30.22MB
SUM->down                    3.96GB
SUM->TOTAL                   3.99GB
---------------Outbound-------------

----------------User---------------
winger->up                   7.91MB
winger->down               978.12MB
alundra->up                 22.31MB
alundra->down                3.01GB
SUM->up                     30.22MB
SUM->down                    3.96GB
SUM->TOTAL                   3.99GB
----------------User---------------

配合 watch 命令,可以持续查看流经 xray 的流量增长情况。使用 reset 参数重置流量统计,即可查看每秒实时流量速度,如:

 watch ./traffic.py reset