网站Logo 大沈博客

安装V2Ray

admin
28
2026-02-16
typora-root-url: images

一、VMware配置

连接光盘配置镜像源

mkdir /mnt/cdrom
mount -t iso9660 /dev/cdrom  /mnt/cdrom/

挂在光盘成功


cd /mnt/cdrom/
cd /etc/yum.repos.d/
mkdir back
mv * back/

备份yum源


cp -a ./back/CentOS-Media.repo CentOS-Media.repo
vim CentOS-Media.repo

更改配置》保存退出


# 更改yum源地址
baseurl=file:///mnt/cdrom/
# 关闭yum源认证
gpgcheck=0
# 开启yum源
enabled=1

清空缓存》 yum clean all

安装软件》yum -y install gcc gcc-c++ lrzsz

安装完成后关闭》shutdown -h now

VMware》右键》快照》拍摄快照》备份镜像

配置阿里云镜像源

# 1. 备份
mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup
wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
​
cd /etc/yum.repos.d/
# 配置阿里云镜像源,删除光盘镜像源
rm -rf CentOS-Media.repo
mv Centos-7.repo CentOS-Base.repo
# 清理yum缓存,并生成新的缓存
yum clean all
yum makecache

或者

配置腾讯云镜像源


# 1. 备份
mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup
wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.cloud.tencent.com/repo/centos7_base.repo
​
cd /etc/yum.repos.d/
# 配置腾讯云镜像源,删除光盘镜像源
rm -rf CentOS-Media.repo
mv centos7_base.repo CentOS-Base.repo
# 清理yum缓存,并生成新的缓存
yum clean all
yum makecache

Epel 镜像


# 1. 备份(如有配置其他epel源)
mv /etc/yum.repos.d/epel.repo /etc/yum.repos.d/epel.repo.backup
mv /etc/yum.repos.d/epel-testing.repo /etc/yum.repos.d/epel-testing.repo.backup
​
# epel(RHEL 7)
wget -O /etc/yum.repos.d/epel.repo https://mirrors.aliyun.com/repo/epel-7.repo
​
cd /etc/yum.repos.d/
mv epel-7.repo epel.repo
# 清理yum缓存,并生成新的缓存
yum clean all
yum makecache

网卡配置


# 第一块网卡桥接模式
vim /etc/sysconfig/network-scripts/ifcfg-ens33
ONBOOT=yes
BOOTPROTO=static
IPADDR=192.168.9.150
NETMASK=255.255.255.0
GATEWAY=192.168.9.1
DNS1=114.114.114.114
DNS2=223.5.5.5
​
# 第二块网卡关闭
vim /etc/sysconfig/network-scripts/ifcfg-ens34
ONBOOT=no
​
# 保存完成》重启网卡
service network restart
​

关闭网卡守护进程

CentOS7

图形化才有NetworkManager


# 查看网卡守护进程状态
systemctl list-unit-files | grep NetworkManager
# 临时关闭网卡守护进程
systemctl stop NetworkManager.service
# 永久关闭网卡守护进程
systemctl disable NetworkManager.service

关闭防火墙

CentOS7


# 查开机启动状态
systemctl list-unit-files | grep fire   
# firewall开机启动
systemctl enable firewalld.service
# 停止firewall
systemctl stop firewalld.service
# 禁止firewall开机启动
systemctl disable firewalld.service 

关闭SELINUX


vim /etc/selinux/config 
​
改SELINUX=disabled》保存退出
[root@node01 ~]# sed -i '/^SELINUX=/ c SELINUX=disabled' /etc/selinux/config
​

重启reboot


# 重启
reboot

二、安装V2Ray

参考:https://jishuzhan.net/article/1932679439594336257

参考:https://www.oryoy.com/news/centos-qing-song-shang-shou-v2ray-ke-hu-duan-pei-zhi-quan-gong-lve-jie-suo-wang-luo-jia-su-xin-ti-ya.html

参考:http://www.rongsp.com/article/128.html

参考:https://v2rayn.la/tutorial/

手动下载 & 解压 V2Ray v5.41.0(修正目录冲突)


# 安装依赖工具
yum install -y wget openssl unzip
​
# 1. 进入临时目录(方便管理下载文件)
cd /tmp
​
​
# 2. 下载V2Ray v5.41.0 Linux x86_64版本
wget https://github.com/v2fly/v2ray-core/releases/download/v5.41.0/v2ray-linux-64.zip
​
​
​
# 3. 创建V2Ray目录结构(符合FHS规范,统一管理)
mkdir -p /usr/local/bin/v2ray       # 存放二进制文件
mkdir -p /usr/local/etc/v2ray       # 存放配置文件
mkdir -p /var/log/v2ray             # 存放日志
mkdir -p /etc/v2ray/cert            # 存放SSL证书
​
# 4. 解压下载的v5.41.0包到临时目录
unzip v2ray-linux-64.zip -d /tmp/v2ray_temp
​
# 删除之前创建的空目录/usr/local/bin/v2ray(仅删除目录,无重要文件)
rm -rf /usr/local/bin/v2ray
​
# 重新移动v2ray可执行文件到/usr/local/bin/(此时无目录冲突)
mv /tmp/v2ray_temp/v2ray /usr/local/bin/
​
# 赋予v2ray可执行权限(确保能运行)
chmod +x /usr/local/bin/v2ray
​
# 验证版本(核心!确认是v5.41.0)
v2ray version
​
​
# 清理临时文件(可选,释放空间)
rm -rf /tmp/v2ray_temp /tmp/v2ray-linux-64.zip

三、Trojan协议配置示例

1、生成 SSL 自签名证书(Trojan 必需)


# 生成证书&私钥(替换your_domain为服务器公网IP/自定义标识)
openssl req -x509 -newkey rsa:4096 -keyout /etc/v2ray/cert/trojan.key -out /etc/v2ray/cert/trojan.crt -days 3650 -nodes \
-subj "/C=CN/ST=Beijing/L=Beijing/O=V2Ray/OU=Trojan/CN=your_domain"
​
# 设置证书权限(提升安全性,仅root可读写私钥)
chmod 644 /etc/v2ray/cert/trojan.key
chmod 644 /etc/v2ray/cert/trojan.crt

2、编写 V2Ray v5.41.0 Trojan 配置文件


# 创建并编辑配置文件
vim /usr/local/etc/v2ray/config.json


{
  "log": {
    "access": "/var/log/v2ray/access.log",
    "error": "/var/log/v2ray/error.log",
    "loglevel": "warning"
  },
  "inbounds": [
    {
      "port": 443,                // Trojan默认端口(隐蔽性强)
      "listen": "0.0.0.0",        // 监听所有网卡
      "protocol": "trojan",       // 启用Trojan协议
      "settings": {
        "clients": [
          {
            "password": "V2Ray@Trojan_2026!"  // 务必修改为强密码!
          }
        ],
        "fallbacks": [
          {
            "dest": 80            // 回落端口:非Trojan流量转发到80
          }
        ]
      },
      "streamSettings": {
        "network": "tcp",
        "security": "tls",        // 启用TLS加密
        "tlsSettings": {
          "serverName": "your_domain",  // 需和证书中的CN值一致(如服务器IP)
          "certificates": [
            {
              "certificateFile": "/etc/v2ray/cert/trojan.crt",  // 证书路径
              "keyFile": "/etc/v2ray/cert/trojan.key"           // 私钥路径
            }
          ]
        }
      }
    }
  ],
  "outbounds": [
    {
      "protocol": "freedom",      // 出站直连外网
      "settings": {}
    }
  ]
}

示例


{
  "log": {
    "access": "/var/log/v2ray/access.log",
    "error": "/var/log/v2ray/error.log",
    "loglevel": "warning"
  },
  "inbounds": [
    {
      "port": 443,
      "listen": "0.0.0.0",
      "protocol": "trojan",
      "settings": {
        "clients": [
          {
            "password": "V2Ray@Trojan_2026!"
          }
        ],
        "fallbacks": [
          {
            "dest": 80
          }
        ]
      },
      "streamSettings": {
        "network": "tcp",
        "security": "tls",
        "tlsSettings": {
          "serverName": "your_domain",
          "certificates": [
            {
              "certificateFile": "/etc/v2ray/cert/trojan.crt",
              "keyFile": "/etc/v2ray/cert/trojan.key"
            }
          ]
        }
      }
    }
  ],
  "outbounds": [
    {
      "protocol": "freedom",
      "settings": {}
    }
  ]
}

四、创建 systemd 服务(管理 V2Ray 进程)

适配 v5.41.0 的服务文件(无 v2ctl 依赖):


# 创建服务文件
vim /etc/systemd/system/v2ray.service

粘贴以下内容并保存:


[Unit]
Description=V2Ray v5.41.0 Service
Documentation=https://www.v2ray.com/
After=network.target nss-lookup.target
​
[Service]
User=root
Group=root
# 仅调用v2ray主程序(无v2ctl),指定配置文件路径
ExecStart=/usr/local/bin/v2ray run -config /usr/local/etc/v2ray/config.json
Restart=on-failure          # 异常退出自动重启
RestartSec=5s                # 重启间隔5秒
LimitNOFILE=1048576          # 提升文件描述符限制
​
[Install]
WantedBy=multi-user.target   # 开机自启

示例


[Unit]
Description=V2Ray v5.41.0 Service
Documentation=https://www.v2ray.com/
After=network.target nss-lookup.target
​
[Service]
User=root
Group=root
​
ExecStart=/usr/local/bin/v2ray run -config /usr/local/etc/v2ray/config.json
Restart=on-failure
RestartSec=5s
LimitNOFILE=1048576
​
[Install]
WantedBy=multi-user.target

五、启动 V2Ray 并验证运行状态


# 1. 重新加载systemd配置(识别新服务)
systemctl daemon-reload
​
# 2. 启动V2Ray服务
systemctl start v2ray
​
# 3. 设置开机自启
systemctl enable v2ray
​
# 4. 检查服务状态(正常显示active (running))
systemctl status v2ray
​
# 5. 验证443端口是否被V2Ray监听
ss -tulnp | grep 443 | grep v2ray

六、开放防火墙 / 安全组端口


# 修改内核参数
vim /etc/sysctl.conf
# 修改
# 开启ipv4路由转发
net.ipv4.ip_forward=1
# 刷新内核参数
[root@centos7 yum.repos.d]# sysctl -p
net.ipv4.ip_forward = 1
​
​
# 安装iptables
yum -y install iptables-services
​
# 开启iptables
systemctl start iptables.service
# 开机自启iptables
systemctl enable iptables.service
# 查开机启动状态
systemctl list-unit-files | grep iptables   
# 查看iptables状态
systemctl status iptables.service
​
# 查看过滤规则
iptables -nL -v --line-numbers
​
# 查看 NAT 规则(确保 MASQUERADE 存在)
iptables -t nat -nL -v --line-numbers
​
# 最前添加规则,放行443端口数据包
iptables -I INPUT 1 -p tcp --dport 443 -j ACCEPT
​
# 将防火墙规则保存
[root@centos7 yum.repos.d]# service iptables save

七、客户端配置说明

客户端(V2RayN/Shadowrocket/Clash 等)配置参数:

参数

取值

协议

Trojan

服务器地址

你的 VPS 公网 IP

端口

443

密码

你配置的强密码(如 V2Ray@Trojan_2026!)

加密方式

无(Trojan 默认无需额外加密)

服务器名称

证书中的 CN 值(your_domain / 服务器 IP)

允许不安全

开启(自签名证书必须开启)

1、windows客户端

安装v2rayN-windows-64.zip

配置Trojan协议

八、进阶版高抗检测 V2Ray(v5.41.0)

1、手动安装 V2Ray v5.41.0(拒绝一键脚本)


# 1. 进入临时目录(方便管理下载文件)
cd /tmp
​
​
# 2. 下载V2Ray v5.41.0 Linux x86_64版本
wget https://github.com/v2fly/v2ray-core/releases/download/v5.41.0/v2ray-linux-64.zip
​
​
​
# 3. 创建V2Ray目录结构(符合FHS规范,统一管理)
mkdir -p /usr/local/bin/v2ray       # 存放二进制文件
mkdir -p /usr/local/etc/v2ray       # 存放配置文件
mkdir -p /var/log/v2ray             # 存放日志
mkdir -p /etc/v2ray/certs           # 存放SSL证书
​
# 4. 解压下载的v5.41.0包到临时目录
unzip v2ray-linux-64.zip -d /tmp/v2ray_temp
​
# 删除之前创建的空目录/usr/local/bin/v2ray(仅删除目录,无重要文件)
rm -rf /usr/local/bin/v2ray
​
# 重新移动v2ray可执行文件到/usr/local/bin/(此时无目录冲突)
cp /tmp/v2ray_temp/v2ray /usr/local/bin
​
# 赋予v2ray可执行权限(确保能运行)
chmod +x /usr/local/bin/v2ray
​
# 验证版本(核心!确认是v5.41.0)
v2ray version
​
​
# 清理临时文件(可选,释放空间)
rm -rf /tmp/v2ray_temp /tmp/v2ray-linux-64.zip

2、生成自签 SSL 证书(高兼容性 + 抗检测)


# 生成自签证书(替换yourdomain.com为任意域名,仅需与配置一致)
openssl req -x509 -newkey rsa:4096 -nodes -keyout /etc/v2ray/certs/server.key -out /etc/v2ray/certs/server.crt -days 3650 -subj "/CN=your-domain.com"
​
# 设置证书权限(提升安全性,仅root可读写私钥)
chmod 644 /etc/v2ray/certs/server.key
chmod 644 /etc/v2ray/certs/server.crt

3、V2Ray 核心配置(多用户 + 抗检测 + 流量统计)

  1. 编辑 V2Ray 配置文件


# 创建并编辑配置文件
vim /usr/local/etc/v2ray/config.json

粘贴以下配置(已标注关键注释,按需修改用户信息):


{
  "log": {
    "loglevel": "info", # 日志级别
    "access": "/var/log/v2ray/access.log", # 这是 Linux 的路径
    "error": "/var/log/v2ray/error.log"
  },
  "api": {
    "tag": "api",
    "services": ["HandlerService", "StatsService"], # 启用流量统计API
    # StatsService(流量统计服务)
    # HandlerService(连接处理管理服务)
  },
  "stats": {}, # 开启流量统计
  "policy": { # 「用户等级维度」的统计规则(V2Ray用户默认等级为0)
    "levels": { # 针对level=0的所有用户生效(你的Trojan用户都是level:0)
      "0": {
        "statsUserUplink": true, # 统计用户上行流量 当值为 true 时,开启当前等级的所有用户的上行流量统计。
        "statsUserDownlink": true # 统计用户下行流量 当值为 true 时,开启当前等级的所有用户的下行流量统计。
      }
    },
    "system": { # 系统/入站维度」的全局统计规则
      "statsInboundUplink": true, # 统计入站总上行流量 当值为 true 时,开启所有入站代理的上行流量统计。
      "statsInboundDownlink": true # 统计入站总下行流量 当值为 true 时,开启所有入站代理的下行流量统计。
      "statsOutboundUplink": true, # 统计出站总上行流量 ( V2Ray 4.26.0+ )当值为 true 时,开启所有出站代理的上行流量统计。
      "statsOutboundDownlink": true # 统计出站总下行流量 ( V2Ray 4.26.0+ ) 当值为 true 时,开启所有出站代理的下行流量统计。
    }
  },
  "inbounds": [
    {
      "tag": "trojan-inbound", # 入站标签(用于流量统计)
      "port": 10086, # 与Nginx回落端口一致
      "listen": "0.0.0.0", # 仅本地监听,通过Nginx转发
      "protocol": "trojan", # Trojan协议
      "settings": {
        "clients": [
          # 多用户配置:每个client对应一个用户(email+密码)
          {
            "password": "user1-password-123",  # 必填,任意字符串。
            "email": "user1@example.com", # 邮件地址,可选,用于标识用户
            "level": 0
          },
          {
            "password": "user2-password-456",  # 必填,任意字符串。
            "email": "user2@example.com", # 邮件地址,可选,用于标识用户
            "level": 0
          },
          {
            "password": "user3-password-789",  # 必填,任意字符串。
            "email": "user3@example.com", # 邮件地址,可选,用于标识用户
            "level": 0
          }
        ],
        "fallbacks": [
          {
            "alpn": "",
            "path": "",
            "dest": 80, # 非TLS流量回落至80端口
            "xver": 0
          }
        ],
        "packetEncoding": "None" # 禁用加密(防止被识别为Trojan流量)
      },
      "streamSettings": {
        "network": "tcp", # TCP协议(配合HTTP头部伪装)
        "security": "tls", # 启用TLS
        "tlsSettings": {
          "serverName": "your-domain.com", # 单个合法SNI 与证书/nginx域名一致
          "alpn": ["h2", "http/1.1"], # ALPN协商(抗DPI关键)
          "certificates": [
            {
              "certificateFile": "/etc/v2ray/certs/server.crt",
              "keyFile": "/etc/v2ray/certs/server.key"
            }
          ],
          "minVersion": "1.2", # 最低TLS1.2,优先1.3
          "rejectUnknownSni": false, # 拒绝未知SNI,增强安全性
​
        },
        "tcpSettings": {
          "header": {
            "type": "http", # HTTP头部伪装(抗DPI核心)
            "response": {
              "version": "1.1",
              "status": "200",
              "reason": "OK",
              "headers": {
                "Content-Type": "text/html; charset=utf-8",
                "Server": "nginx/1.20.1", # 模拟Nginx服务器
                "Cache-Control": "no-cache",
                "Pragma": "no-cache",
                "Date": "%NOW%",
                "Content-Length": "2048"
              }
            }
          }
        }
      }
    },
    {
      "tag": "api",
      "listen": "127.0.0.1",
      "port": 10085,
      "protocol": "dokodemo-door",
      "settings": {
        "address": "127.0.0.1"
      }
    }
  ],
  "outbounds": [
    {
      "protocol": "freedom",
      "tag": "direct" # 直连出站(代理流量的最终出口)
    },
    {
      "protocol": "blackhole",
      "tag": "blocked" # 黑洞出站(阻断指定流量)
    }
  ],
  "routing": {
    "settings": {
      "rules": [
        {
          "inboundTag": [
            "api"
          ],
          "outboundTag": "api",
          "type": "field"
        }
      ]
    },
    "strategy": "rules"
  }
}
​

示例


{
  "log": {
    "loglevel": "info",
    "access": "/var/log/v2ray/access.log",
    "error": "/var/log/v2ray/error.log"
  },
  "api": {
    "tag": "api",
    "services": ["HandlerService", "StatsService"]
  },
  "stats": {},
  "policy": {
    "levels": {
      "0": {
        "statsUserUplink": true,
        "statsUserDownlink": true
      }
    },
    "system": {
      "statsInboundUplink": true,
      "statsInboundDownlink": true,
      "statsOutboundUplink": true,
      "statsOutboundDownlink": true
    }
  },
  "inbounds": [
    {
      "tag": "trojan-inbound",
      "port": 51302,
      "listen": "0.0.0.0",
      "protocol": "trojan",
      "settings": {
        "clients": [
          {
            "password": "5GPRYPMijRORt7dD",
            "email": "user1@example.com",
            "level": 0
          },
          {
            "password": "yvnqIOq3pi5KvEqI",
            "email": "user2@example.com",
            "level": 0
          },
          {
            "password": "LsDhAWJl27GKrX7a",
            "email": "user3@example.com",
            "level": 0
          }
        ],
        "fallbacks": [
          {
            "alpn": "",
            "path": "",
            "dest": 80,
            "xver": 0
          }
        ],
        "packetEncoding": "None"
      },
      "streamSettings": {
        "network": "tcp",
        "security": "tls",
        "tlsSettings": {
          "serverName": "your-domain.com",
          "alpn": ["h2", "http/1.1"],
          "certificates": [
            {
              "certificateFile": "/etc/v2ray/certs/server.crt",
              "keyFile": "/etc/v2ray/certs/server.key"
            }
          ],
          "minVersion": "1.2",
          "rejectUnknownSni": false
        },
        "tcpSettings": {
          "header": {
            "type": "http",
            "response": {
              "version": "1.1",
              "status": "200",
              "reason": "OK",
              "headers": {
                "Content-Type": "text/html; charset=utf-8",
                "Server": "nginx/1.20.1",
                "Cache-Control": "no-cache",
                "Pragma": "no-cache",
                "Date": "%NOW%",
                "Content-Length": "2048"
              }
            }
          }
        }
      }
    },
    {
      "tag": "api",
      "listen": "127.0.0.1",
      "port": 46465,
      "protocol": "dokodemo-door",
      "settings": {
        "address": "127.0.0.1"
      }
    }
  ],
  "outbounds": [
    {
      "protocol": "freedom",
      "tag": "direct"
    },
    {
      "protocol": "blackhole",
      "tag": "blocked"
    }
  ],
  "routing": {
    "settings": {
      "rules": [
        {
          "inboundTag": [
            "api"
          ],
          "outboundTag": "api",
          "type": "field"
        }
      ]
    },
    "strategy": "rules"
  }
}
​


# 验证配置文件语法(关键)
[root@rockylinux9 v2ray]# v2ray test -config /usr/local/etc/v2ray/config.json
V2Ray 5.41.0 (V2Fly, a community-driven edition of V2Ray.) Custom (go1.24.2 linux/amd64)
A unified platform for anti-censorship.
Configuration OK.

4、创建 systemd 服务(管理 V2Ray 进程)

适配 v5.41.0 的服务文件(无 v2ctl 依赖):


# 创建服务文件
vim /etc/systemd/system/v2ray.service

粘贴以下内容并保存:


[Unit]
Description=V2Ray v5.41.0 Service
Documentation=https://www.v2ray.com/
After=network.target nss-lookup.target
​
[Service]
User=root
Group=root
# 仅调用v2ray主程序(无v2ctl),指定配置文件路径
ExecStart=/usr/local/bin/v2ray run -config /usr/local/etc/v2ray/config.json
Restart=on-failure          # 异常退出自动重启
RestartSec=5s                # 重启间隔5秒
LimitNOFILE=1048576          # 提升文件描述符限制
​
[Install]
WantedBy=multi-user.target   # 开机自启

示例


[Unit]
Description=V2Ray v5.41.0 Service
Documentation=https://www.v2ray.com/
After=network.target nss-lookup.target
​
[Service]
User=root
Group=root
​
ExecStart=/usr/local/bin/v2ray run -config /usr/local/etc/v2ray/config.json
Restart=on-failure
RestartSec=5s
LimitNOFILE=1048576
​
[Install]
WantedBy=multi-user.target

5、启动 V2Ray 并验证运行状态


# 1. 重新加载systemd配置(识别新服务)
systemctl daemon-reload
​
# 2. 启动V2Ray服务
systemctl start v2ray
​
# 3. 设置开机自启
systemctl enable v2ray
​
# 4. 检查服务状态(正常显示active (running))
systemctl status v2ray
​
# 5. 验证10086 10085 端口是否被V2Ray监听
ss -tulnp | grep -E '10086|10085' | grep v2ray

6、开放防火墙 / 安全组端口


# 修改内核参数
vim /etc/sysctl.conf
# 修改
# 开启ipv4路由转发
net.ipv4.ip_forward=1
# 刷新内核参数
[root@centos7 yum.repos.d]# sysctl -p
net.ipv4.ip_forward = 1
​
​
# 安装iptables
yum -y install iptables-services
​
# 开启iptables
systemctl start iptables.service
# 开机自启iptables
systemctl enable iptables.service
# 查开机启动状态
systemctl list-unit-files | grep iptables   
# 查看iptables状态
systemctl status iptables.service
​
# 查看过滤规则
iptables -nL -v --line-numbers
​
# 查看 NAT 规则(确保 MASQUERADE 存在)
iptables -t nat -nL -v --line-numbers
​
# 最前添加规则,放行443端口数据包
iptables -I INPUT 1 -p tcp --dport 80 -j ACCEPT
iptables -I INPUT 1 -p tcp --dport 443 -j ACCEPT
iptables -I INPUT 1 -p tcp --dport 10086 -j ACCEPT
​
# 将防火墙规则保存
[root@centos7 yum.repos.d]# service iptables save

7、流量统计使用方法


# 先查看你当前版本的api命令正确用法
[root@rockylinux9 v2ray]# v2ray help api
v2ray api provides tools to manipulate V2Ray via its API.
​
Usage:
​
    v2ray api <command> [arguments]
​
The commands are:
​
    log          log operations
    stats        query statistics
    bi           balancer information
    bo           balancer override
    adi          add inbounds
    ado          add outbounds
    rmi          remove inbounds
    rmo          remove outbounds
​
Use "v2ray help api <command>" for more information about a command.
​
# 先查看stats子命令的具体用法(关键)
[root@rockylinux9 v2ray]# v2ray help api stats
usage: v2ray api stats [--server=127.0.0.1:8080] [pattern]...
​
Query statistics from V2Ray.
​
> Make sure you have "StatsService" set in "config.api.services" 
of server config.
​
Arguments:
​
    -regexp
        The patterns are using regexp.
​
    -reset
        Reset counters to 0 after fetching their values.
​
    -runtime
        Get runtime statistics.
​
    -json
        Use json output.
​
    -s, -server <server:port>
        The API server address. Default 127.0.0.1:8080
​
    -t, -timeout <seconds>
        Timeout seconds to call API. Default 3
​
Example:
​
    v2ray api stats -runtime
    v2ray api stats node1
    v2ray api stats -json node1 node2
    v2ray api stats -regexp 'node1.+downlink'
[root@rockylinux9 v2ray]# 
​

一、核心查询命令(适配你的场景)

1. 基础查询(纯文本输出,最简洁)


# 查询trojan-inbound入站上行总流量(核心命令)
v2ray api stats -s 127.0.0.1:46465 'inbound>>>trojan-inbound>>>traffic>>>uplink'
​
# 查询trojan-inbound入站下行总流量
v2ray api stats -s 127.0.0.1:46465 'inbound>>>trojan-inbound>>>traffic>>>downlink'
​
# 查询user1@example.com的下行流量
v2ray api stats -s 127.0.0.1:46465 'user>>>user3@example.com>>>traffic>>>downlink'
​
# 查询user1@example.com的上行流量
v2ray api stats -s 127.0.0.1:46465 'user>>>user3@example.com>>>traffic>>>uplink'

2.JSON 格式输出(更易读取 / 脚本解析)

推荐用-json参数,输出结构化 JSON,方便后续处理:


# JSON格式查询入站上行流量
v2ray api stats -s 127.0.0.1:46465 -json 'inbound>>>trojan-inbound>>>traffic>>>uplink'
​
# JSON格式查询单个用户下行流量
v2ray api stats -s 127.0.0.1:46465 -json 'user>>>user1@example.com>>>traffic>>>downlink'

3.正则批量查询(高效查多个指标)

-regexp参数可批量匹配多个 pattern,比如查询所有用户的下行流量:


# 查询所有用户的下行流量(正则匹配user开头+downlink结尾)
v2ray api stats -s 127.0.0.1:46465 -regexp 'user>>>.*>>>traffic>>>downlink'
​
# 查询所有用户的上下行流量
v2ray api stats -s 127.0.0.1:46465 -regexp 'user>>>.*>>>traffic>>>(uplink|downlink)'
​
​
# 查询所有入站的上下行流量
v2ray api stats -s 127.0.0.1:46465 -regexp 'inbound>>>.*>>>traffic>>>(uplink|downlink)'

4. 查询后重置计数器(可选)

-reset参数可在查询流量后清空该指标的计数(适合定期统计):


# 查询并重置trojan-inbound上行流量计数器
v2ray api stats -s 127.0.0.1:46465 -reset 'inbound>>>trojan-inbound>>>traffic>>>uplink'
​
# 查询并重置所有用户的上下行流量
v2ray api stats -s 127.0.0.1:46465 -reset -regexp 'user>>>.*>>>traffic>>>(uplink|downlink)'
​
# 查询并重置所有入站的上下行流量
v2ray api stats -s 127.0.0.1:46465 -reset -regexp 'inbound>>>.*>>>traffic>>>(uplink|downlink)'

​
uplink:上行流量,客户端 → 服务器(用户发出去的)
downlink:下行流量,服务器 → 客户端(用户收到的)
​
总结:
uplink = 上行 = 客户端发给服务器(上传、请求)
downlink = 下行 = 服务器发给客户端(下载、响应)

8、动态添加 / 删除 Trojan 用户


# 先查看你当前版本的api命令正确用法
[root@rockylinux9 v2ray]# v2ray help api
v2ray api provides tools to manipulate V2Ray via its API.
​
Usage:
​
    v2ray api <command> [arguments]
​
The commands are:
​
    log          log operations
    stats        query statistics
    bi           balancer information
    bo           balancer override
    adi          add inbounds
    ado          add outbounds
    rmi          remove inbounds
    rmo          remove outbounds
​
Use "v2ray help api <command>" for more information about a command.
​
# 先查看rmi子命令的具体用法(关键)
[root@rockylinux9 v2ray]# v2ray help api rmi
usage: v2ray api rmi [--server=127.0.0.1:8080] [c1.json] [dir1]...
​
Remove inbounds from V2Ray.
​
> Make sure you have "HandlerService" set in "config.api.services" 
of server config.
​
Arguments:
​
    -format <format>
        The input format.
        Available values: "auto", "json", "toml", "yaml"
        Default: "auto"
​
    -r
        Load folders recursively.
​
    -tags
        The input are tags instead of config files
​
    -s, -server <server:port>
        The API server address. Default 127.0.0.1:8080
​
    -t, -timeout <seconds>
        Timeout seconds to call API. Default 3
​
Example:
​
    v2ray api rmi dir
    v2ray api rmi c1.json c2.yaml
    v2ray api rmi -tags tag1 tag2
    
# 先查看adi子命令的具体用法(关键)
[root@rockylinux9 v2ray]# v2ray help api adi
usage: v2ray api adi [--server=127.0.0.1:8080] [c1.json] [dir1]...
​
Add inbounds to V2Ray.
​
> Make sure you have "HandlerService" set in "config.api.services" 
of server config.
​
Arguments:
​
    -format <format>
        The input format.
        Available values: "auto", "json", "toml", "yaml"
        Default: "auto"
​
    -r
        Load folders recursively.
​
    -s, -server <server:port>
        The API server address. Default 127.0.0.1:8080
​
    -t, -timeout <seconds>
        Timeout seconds to call API. Default 3
​
Example:
​
    v2ray api adi dir
    v2ray api adi c1.json c2.yaml
​
​

一、动态添加/删除 Trojan 用户

核心思路

通过HandlerService.ModifyInbound API,向trojan-inboundclients数组中追加新用户(保留原有用户,不覆盖)。

步骤 1:构造添加/删除用户的 JSON 参数

新建一个临时 JSON 文件(如trojan-inbound.json),内容如下(替换新用户的passwordemail):

vim /usr/local/etc/v2ray/trojan-inbound.json


{
  "tag": "trojan-inbound",
  "port": 51302,
  "listen": "0.0.0.0",
  "protocol": "trojan",
  "settings": {
    "clients": [
      {
        "password": "5GPRYPMijRORt7dD",
        "email": "user1@example.com",
        "level": 0
      },
      {
        "password": "yvnqIOq3pi5KvEqI",
        "email": "user2@example.com",
        "level": 0
      },
      {
        "password": "LsDhAWJl27GKrX7a",
        "email": "user3@example.com",
        "level": 0
      },
      {
        "password": "j6jsMy5RXkD4XKzA",
        "email": "user4@example.com",
        "level": 0
      }
    ],
    "fallbacks": [
      {
        "alpn": "",
        "path": "",
        "dest": 80,
        "xver": 0
      }
    ],
    "packetEncoding": "None"
  },
  "streamSettings": {
    "network": "tcp",
    "security": "tls",
    "tlsSettings": {
      "serverName": "your-domain.com",
      "alpn": [
        "h2",
        "http/1.1"
      ],
      "certificates": [
        {
          "certificateFile": "/etc/v2ray/certs/server.crt",
          "keyFile": "/etc/v2ray/certs/server.key"
        }
      ],
      "minVersion": "1.2",
      "rejectUnknownSni": false
    },
    "tcpSettings": {
      "header": {
        "type": "http",
        "response": {
          "version": "1.1",
          "status": "200",
          "reason": "OK",
          "headers": {
            "Content-Type": "text/html; charset=utf-8",
            "Server": "nginx/1.20.1",
            "Cache-Control": "no-cache",
            "Pragma": "no-cache",
            "Date": "%NOW%",
            "Content-Length": "2048"
          }
        }
      }
    }
  }
}

步骤 2:执行添加/删除命令

# 删除trojan-inbound入站(会直接关闭51302端口的Trojan服务)
v2ray api rmi --server=127.0.0.1:46465 -tags trojan-inbound
​
# 恢复:重新执行adi命令导入trojan-inbound.json即可
v2ray api adi --server=127.0.0.1:46465 /usr/local/etc/v2ray/trojan-inbound.json
​
netstat -ntulp | grep -E '46465|51302'
​
​
# 查询所有用户的上下行流量
v2ray api stats -s 127.0.0.1:46465 -regexp 'user>>>.*>>>traffic>>>(uplink|downlink)'
​
​
# 查询所有入站的上下行流量
v2ray api stats -s 127.0.0.1:46465 -regexp 'inbound>>>.*>>>traffic>>>(uplink|downlink)'

9、客户端配置说明

1、windows客户端

九、官方文档

地址:https://www.v2fly.org/

地址:https://guide.v2fly.org/

地址:https://www.v2ray.com/

地址:https://toutyrater.github.io/


V2Ray
源代码以官方发布的安装包,使用 MIT 协议授权。包括以下代码仓库中的源代码及安装包:
​
v2fly/v2ray-core
https://www.github.com/v2fly/v2ray-core/
​
官方网站
官方网站(v2fly.org)以 知识共享署名 4.0 国际许可协议 协议授权。
https://www.v2fly.org/
​
​
包括网站中所有可见的文字内容和图片。
包括 Project V 图标文件。
包括生成网站所使用到的源代码,即 v2fly/v2fly-github-io。
软件截图和其它文件
https://github.com/v2fly/v2fly-github-io
​
# 第三方图形客户端
https://www.v2fly.org/awesome/tools.html
​
# trojan文档
https://www.v2fly.org/config/protocols/trojan.html
​
# 全球网络加速服务
https://docs.bridgehead.link/docs/intro
​
# v2ray-core 流量统计 StatsService 使用要点
https://gist.github.com/boypt/80d9ecaaa7f3c799c525e91f3c0b35d1

动物装饰