在存储空间有限的 OpenWrt 系统上,直接将大型应用安装到闪存会占用宝贵的存储资源。为了减轻负担,可以将 Xray 安装到内存中(/tmp 目录),并在开机时自动下载和解压,确保每次启动后都能正常运行。

问题背景

在一些路由设备上,闪存容量有限,而 Xray 核心二进制文件及其依赖解压后体积较大。如果直接安装到闪存,不仅浪费空间,还可能影响系统更新和其他软件的安装。

将 Xray 放到 /tmp 目录运行,能有效减少闪存写入并节省空间。/tmp 是 tmpfs 文件系统,位于内存中,速度快且不会长期占用存储。不过,这也意味着重启后内容会丢失,因此需要一个自动化安装机制。

关键挑战

在某些代理插件中,如果启用了 Localhost Proxy(让路由器自身访问外网也走代理),安装脚本的下载过程会被强制通过代理转发。而代理需要依赖 Xray 才能工作,这就会导致死循环:

  1. 下载 Xray → 需要代理
  2. 代理运行 → 需要 Xray
  3. 最终 Xray 永远无法下载成功

为避免这种情况,应在安装脚本运行时关闭 Localhost Proxy,让路由器自身直连外网下载。

自动安装脚本

以下脚本会在系统启动时自动下载并解压 Xray 到 /tmp/xray 目录,二进制文件路径为 /tmp/xray/xray

#!/bin/sh /etc/rc.common
START=99   # 启动顺序靠后,保证网络就绪

start() {
  LOG="/tmp/xray-install.log"
  TMPDIR="/tmp/xray"
  ZIP="$TMPDIR/xray.zip"
  URL="https://github.com/XTLS/Xray-core/releases/latest/download/Xray-linux-arm32-v7a.zip"

  # 创建目录与日志文件
  mkdir -p "$TMPDIR"
  exec >>"$LOG" 2>&1
  echo "==== $(date) start xraytmp ===="

  # 等待网络(最多 90 秒)
  i=0
  while [ $i -lt 30 ]; do
    nslookup github.com >/dev/null 2>&1 && break
    ping -c1 -W1 1.1.1.1 >/dev/null 2>&1 && break
    sleep 3; i=$((i+1))
  done
  echo "[xraytmp] network checked: i=$i"

  # 清理旧文件
  rm -rf "$TMPDIR"/*
  
  # 下载 Xray 压缩包
  echo "[xraytmp] downloading..."
  if command -v wget >/dev/null 2>&1; then
    wget -O "$ZIP" "$URL"
  else
    curl -L "$URL" -o "$ZIP"
  fi

  [ -s "$ZIP" ] || { echo "[xraytmp] download failed"; echo "==== $(date) done ===="; return 1; }

  # 解压到 /tmp/xray
  echo "[xraytmp] unzip..."
  unzip -o "$ZIP" -d "$TMPDIR" || { echo "[xraytmp] unzip failed"; echo "==== $(date) done ===="; return 1; }

  # 统一设置二进制路径
  if [ -f "$TMPDIR/xray" ]; then
    chmod +x "$TMPDIR/xray"
  elif [ -f "$TMPDIR/Xray" ]; then
    mv "$TMPDIR/Xray" "$TMPDIR/xray"
    chmod +x "$TMPDIR/xray"
  else
    F=$(find "$TMPDIR" -maxdepth 2 -type f -name xray | head -n1)
    [ -n "$F" ] && mv -f "$F" "$TMPDIR/xray" && chmod +x "$TMPDIR/xray"
  fi

  if [ ! -f "$TMPDIR/xray" ]; then
    echo "[xraytmp] binary not found after unzip"
    echo "==== $(date) done ===="; return 1
  fi

  "$TMPDIR/xray" -version || true
  echo "[xraytmp] installed at $TMPDIR/xray"
  echo "==== $(date) done ===="
}

部署步骤

  1. 将脚本保存为 /etc/init.d/xraytmpvi /etc/init.d/xraytmp 粘贴脚本内容并保存。
  2. 赋予可执行权限并设置开机启动: chmod +x /etc/init.d/xraytmp /etc/init.d/xraytmp enable
  3. 确认开机启动链接已创建: ls -l /etc/rc.d/S99xraytmp
  4. 重启系统,开机后检查: /tmp/xray/xray -version tail -n +1 /tmp/xray-install.log

插件配置

在 Xray 管理插件中,将 Xray App Path 设置为:

/tmp/xray/xray

确保 Localhost Proxy 关闭,以避免安装阶段出现死循环问题。

总结

通过将 Xray 安装到 /tmp 并在开机时自动下载,可以在存储空间有限的 OpenWrt 系统中稳定运行 Xray,同时避免对闪存的长期占用。
配合关闭 Localhost Proxy,可彻底解决“代理依赖下载,下载依赖代理”的启动死循环问题。

Leave a Reply

Your email address will not be published. Required fields are marked *