Skip to content

sing-box AnyTLS 客户端指南

本文档介绍如何在 Linux 系统上安装、配置并使用 sing-box 作为本地代理客户端


温馨提示

目前已经支持解析

1.anytls 2.vless reality 3.trojan grpc

3种协议

下载与安装

# 下载二进制包
wget https://ap-us-files-prod.neworld.today/new/linux/sing-box-1.13.11-linux-amd64.tar.gz

# 解压
tar -xzf sing-box-1.13.11-linux-amd64.tar.gz

# 安装到系统路径
mv sing-box-1.13.11-linux-amd64/sing-box /usr/local/bin/

# 验证安装
sing-box version

# 清理临时文件
rm -rf sing-box-1.13.11-linux-amd64.tar.gz sing-box-1.13.11-linux-amd64/

正常输出(部分省略)

sing-box version 1.13.11

Environment: go1.25.9 linux/amd64
Tags: ...
Revision: ...
CGO: disabled

创建 systemd 服务

创建服务配置目录及 systemd 单元文件:

# 创建配置目录
mkdir -p /etc/sing-box

# 写入 systemd 服务文件
cat > /etc/systemd/system/sing-box.service << 'EOF'
[Unit]
Description=sing-box service
After=network.target

[Service]
Type=simple
User=root
ExecStart=/usr/local/bin/sing-box run -c /etc/sing-box/config.json
Restart=on-failure
RestartSec=3s

[Install]
WantedBy=multi-user.target
EOF

# 重新加载 systemd
systemctl daemon-reload

自动写入配置

复制并执行下面的内容,执行后的后续操作,请看代码后的说明

cat > /tmp/setup-singbox.py << 'PYEOF'
import json, os, sys, subprocess, urllib.parse

# ───────────────────────────────────────────
#  交互式输入节点链接
# ───────────────────────────────────────────
print("=" * 55)
print("  sing-box 一键配置工具")
print("  支持: AnyTLS / VLESS Reality / Trojan gRPC")
print("=" * 55)
try:
    URL = input("📎 请粘贴节点链接: ").strip()
except (EOFError, KeyboardInterrupt):
    print("\n❌ 已取消")
    sys.exit(1)

if not URL:
    print("❌ 链接不能为空")
    sys.exit(1)

# ───────────────────────────────────────────
#  解析链接 → 构造 outbound
# ───────────────────────────────────────────
try:
    p      = urllib.parse.urlparse(URL)
    scheme = p.scheme.lower()          # anytls / vless / trojan
    params = dict(urllib.parse.parse_qsl(p.query))
    name   = urllib.parse.unquote(p.fragment) or "proxy"
    uuid_or_pwd = p.username          # vless/trojan 均用 username 字段
    server      = p.hostname
    port        = p.port
except Exception as e:
    print(f"❌ 链接解析失败: {e}")
    sys.exit(1)

if not all([uuid_or_pwd, server, port]):
    print("❌ 链接缺少必要字段(用户名 / server / port)")
    sys.exit(1)

# ── 协议分支 ────────────────────────────────
if scheme == "vless":
    # ---- VLESS + Reality (TCP / XTLS Vision) ----
    flow     = params.get("flow", "")          # xtls-rprx-vision
    sni      = params.get("sni", server)
    fp       = params.get("fp", "chrome")
    pbk      = params.get("pbk", "")          # public key
    sid      = params.get("sid", "")          # short id
    net_type = params.get("type", "tcp")

    outbound = {
        "type":        "vless",
        "tag":         name,
        "server":      server,
        "server_port": port,
        "uuid":        uuid_or_pwd,
        "flow":        flow,
        "tls": {
            "enabled":     True,
            "server_name": sni,
            "utls": {
                "enabled":     True,
                "fingerprint": fp
            },
            "reality": {
                "enabled":    True,
                "public_key": pbk,
                "short_id":   sid
            }
        }
    }

    # transport(tcp 时不需要 transport 字段)
    if net_type == "ws":
        outbound["transport"] = {
            "type": "ws",
            "path": params.get("path", "/")
        }

    proto_label = "VLESS + Reality"
    info_lines = [
        f"🆔 UUID        : {uuid_or_pwd}",
        f"🌐 服务器      : {server}:{port}",
        f"🔀 Flow        : {flow}",
        f"🔑 PublicKey   : {pbk}",
        f"🔖 ShortId     : {sid}",
        f"🌍 SNI         : {sni}",
        f"🖥  指纹        : {fp}",
    ]

elif scheme == "trojan":
    # ---- Trojan + gRPC + TLS ----
    sni          = params.get("sni", server)
    service_name = params.get("serviceName") or params.get("path", "mygrpc")
    net_type     = params.get("type", "tcp")   # grpc / tcp / ws
    insecure     = (
        params.get("insecure",      "0") == "1" or
        params.get("allowInsecure", "0") == "1"
    )

    outbound = {
        "type":        "trojan",
        "tag":         name,
        "server":      server,
        "server_port": port,
        "password":    uuid_or_pwd,
        "tls": {
            "enabled":     True,
            "server_name": sni,
            "insecure":    insecure
        }
    }

    # gRPC transport
    if net_type == "grpc" or params.get("obfs") == "grpc":
        outbound["transport"] = {
            "type":         "grpc",
            "service_name": service_name
        }

    proto_label = "Trojan + gRPC"
    info_lines = [
        f"🔑 密码        : {uuid_or_pwd}",
        f"🌐 服务器      : {server}:{port}",
        f"🌍 SNI         : {sni}",
        f"📡 serviceName : {service_name}",
        f"🔓 insecure    : {insecure}",
    ]

elif scheme == "anytls":
    # ---- AnyTLS(原逻辑保留)----
    tls_enabled = params.get("security", "") == "tls"
    insecure    = (
        params.get("insecure",      "0") == "1" or
        params.get("allowInsecure", "0") == "1"
    )

    outbound = {
        "type":        "anytls",
        "tag":         name,
        "server":      server,
        "server_port": port,
        "password":    uuid_or_pwd,
        "tls": {
            "enabled":     tls_enabled,
            "server_name": server,
            "insecure":    insecure
        }
    }

    proto_label = "AnyTLS"
    info_lines = [
        f"🔑 密码        : {uuid_or_pwd}",
        f"🌐 服务器      : {server}:{port}",
        f"🔒 TLS         : {tls_enabled}  insecure: {insecure}",
    ]

else:
    print(f"❌ 不支持的协议: {scheme}")
    print("   目前支持: vless / trojan / anytls")
    sys.exit(1)

# ───────────────────────────────────────────
#  组装完整配置
# ───────────────────────────────────────────
config = {
    "log": { "level": "info" },
    "inbounds": [
        {
            "type":        "socks",
            "tag":         "socks-in",
            "listen":      "127.0.0.1",
            "listen_port": 3080
        },
        {
            "type":        "http",
            "tag":         "http-in",
            "listen":      "127.0.0.1",
            "listen_port": 3081
        }
    ],
    "outbounds": [
        outbound,
        { "type": "direct", "tag": "direct" }
    ],
    "route": { "final": name }
}

# ───────────────────────────────────────────
#  写入配置文件
# ───────────────────────────────────────────
CONFIG_PATH = "/etc/sing-box/config.json"
try:
    os.makedirs(os.path.dirname(CONFIG_PATH), exist_ok=True)
    with open(CONFIG_PATH, "w") as f:
        json.dump(config, f, indent=2, ensure_ascii=False)
except PermissionError:
    print("❌ 无写入权限,请用 sudo 运行此脚本")
    sys.exit(1)
except Exception as e:
    print(f"❌ 写入失败: {e}")
    sys.exit(1)

print()
print(f"✅ 配置已写入   : {CONFIG_PATH}")
print(f"📌 节点名称    : {name}")
print(f"🚀 协议类型    : {proto_label}")
for line in info_lines:
    print(line)
print(f"🧦 SOCKS5      : 127.0.0.1:3080")
print(f"🌍 HTTP 代理   : 127.0.0.1:3081")
print()

# ───────────────────────────────────────────
#  sing-box 配置校验
# ───────────────────────────────────────────
print("─" * 55)
print("🔍 正在校验配置文件...")
check = subprocess.run(
    ["sing-box", "check", "-c", CONFIG_PATH],
    capture_output=True, text=True
)
if check.returncode != 0:
    print("❌ 配置校验失败,已终止重启:")
    print(check.stderr or check.stdout)
    sys.exit(1)
print("✅ 配置校验通过")

# ───────────────────────────────────────────
#  重启 / 启用 systemd 服务
# ───────────────────────────────────────────
print("─" * 55)
print("🔄 正在重启 sing-box 服务...")
for cmd in [
    ["systemctl", "enable",  "sing-box"],
    ["systemctl", "restart", "sing-box"],
]:
    ret   = subprocess.run(cmd, capture_output=True, text=True)
    label = " ".join(cmd[1:])
    if ret.returncode == 0:
        print(f"✅ systemctl {label}")
    else:
        print(f"⚠️  systemctl {label} 失败:")
        print(ret.stderr or ret.stdout)

# ───────────────────────────────────────────
#  显示服务状态
# ───────────────────────────────────────────
print("─" * 55)
status = subprocess.run(
    ["systemctl", "status", "sing-box", "--no-pager", "-l"],
    capture_output=True, text=True
)
print(status.stdout or status.stderr)
PYEOF

# 运行脚本(需要 root 权限)
python3 /tmp/setup-singbox.py

脚本说明

脚本会自动完成以下操作:

  1. 解析粘贴的节点链接(支持 AnyTLS 格式)
  2. 生成 /etc/sing-box/config.json
  3. 校验配置合法性
  4. 重启并启用 sing-box 服务

导入配置

执行脚本时会遇到脚本要求粘贴节点链接

root@debian:~# python3 /tmp/setup-singbox.py
=======================================================
sing-box AnyTLS 一键配置工具
=======================================================
📎 请粘贴节点链接:

内容是在用户中心的节点列表获取,点击如图所示的复制按钮

警告

有时候复制配置会得到两行,或多行链接(因为有的节点有 ipv6 入口,或者配置了国外中转入口),不能直接填写,可以新建一个 txt 文件,然后粘贴复制的内容到 txt 文件中,重新选择一行内容复制,再粘贴给上面的脚本读取

正常输出(部分内容使用 xxx 隐去)

 配置已写入 : /etc/sing-box/config.json
📌 节点名称   : California (美国) B26
🌐 服务器     : xxx:xxx
🔑 密码       : xxx
🔒 TLS        : True  insecure: False
🧦 SOCKS5     : 127.0.0.1:3080
🌍 HTTP 代理  : 127.0.0.1:3081

───────────────────────────────────────────────────────
🔍 正在校验配置文件...
✅ 配置校验通过
───────────────────────────────────────────────────────
🔄 正在重启 sing-box 服务...
✅ systemctl enable sing-box
✅ systemctl restart sing-box
───────────────────────────────────────────────────────
● sing-box.service - sing-box service
     Loaded: loaded (/etc/systemd/system/sing-box.service; enabled; vendor preset: enabled)
     Active: active (running) since Thu 2026-05-14 07:56:01 UTC; 19ms ago
   Main PID: 92970 (sing-box)
      Tasks: 6 (limit: 515)
     Memory: 2.1M
        CPU: 11ms
     CGroup: /system.slice/sing-box.service
             └─92970 /usr/local/bin/sing-box run -c /etc/sing-box/config.json

May 14 07:56:01 krc01 systemd[1]: Started sing-box service.

此时,客户端已经在工作了,可以使用下面的命令检查工作状态

curl ipv4.ip.sb --socks5 127.0.0.1:3080

正常输出(根据选择节点的不同,内容将有差异,是正常情况)

当前 IP:154.xx.xx.xx  来自于:美国 加利福尼亚州 洛杉矶  cogentco.com

服务启动后将监听以下本地端口:

协议 地址 用途
SOCKS5 127.0.0.1:3080 通用代理,支持 TCP/UDP
HTTP 127.0.0.1:3081 HTTP/HTTPS 代理

温馨提示

如何为 git wget curl 配置代理,或是你需要走代理的程序配置代理,可以询问各大 AI


启动与管理服务

温馨提示

下面列出的命令不需要执行,仅做说明之用

# 启动并设置开机自启
systemctl enable --now sing-box

# 查看运行状态
systemctl status sing-box

# 重启服务
systemctl restart sing-box

# 停止服务
systemctl stop sing-box

# 实时查看日志
journalctl -u sing-box -f

# 查看最近 100 行日志
journalctl -u sing-box -n 100 --no-pager

卸载与清理

注意

执行卸载操作将停止代理服务并删除所有相关文件,请确认不再需要后再操作。

第一步:停止并禁用服务

systemctl stop sing-box
systemctl disable sing-box

第二步:删除 systemd 服务文件

rm -f /etc/systemd/system/sing-box.service
systemctl daemon-reload
systemctl reset-failed

第三步:删除二进制文件与配置

# 删除主程序
rm -f /usr/local/bin/sing-box

# 删除配置目录(包含 config.json)
rm -rf /etc/sing-box/

第四步:清理临时脚本(如有)

rm -f /tmp/setup-singbox.py

验证卸载完成

# 确认二进制已删除
which sing-box && echo "未删除" || echo "✅ 已删除"

# 确认服务已移除
systemctl status sing-box 2>&1 | grep -q "not found" && echo "✅ 服务已移除"

# 确认配置目录已删除
[ -d /etc/sing-box ] && echo "目录仍存在" || echo "✅ 配置目录已删除"