Openwrt配置Cloudflare Tunnel(cloudflared)及自启动脚本

描述

在Openwrt中使用cloudflared,可直接使用二进制文件进行配置。自启动相关脚本参考ubuntu下cloudflared service创建的脚本内容修改而来。

相关资料

配置及脚本

  1. 安装procps-ng-ps
    opkg update && opkg install procps-ng-ps
  2. 下载cloudflared到/usr/bin下,添加可执行权限
  3. 创建Openwrt启动脚本/etc/init.d/cloudflared,配置token,相关内容如下
    #!/bin/sh /etc/rc.common
    # For RedHat and cousins:
    # chkconfig: 2345 99 01
    # description: cloudflared
    # processname: /usr/bin/cloudflared
    ### BEGIN INIT INFO
    # Provides:          /usr/bin/cloudflared
    # Required-Start:
    # Required-Stop:
    # Default-Start:     2 3 4 5
    # Default-Stop:      0 1 6
    # Short-Description: cloudflared
    # Description:       cloudflared agent
    ### END INIT INFO
    name=cloudflared
    cmd="/usr/bin/cloudflared --pidfile /var/run/$name.pid --autoupdate-freq 24h0m0s tunnel run --token <token>" #replace <token>
    pid_file="/var/run/$name.pid"
    stdout_log="/var/log/$name.log"
    stderr_log="/var/log/$name.err"
    [ -e /etc/sysconfig/$name ] && . /etc/sysconfig/$name
    get_pid() {
    cat "$pid_file"
    }
    is_running() {
    [ -f "$pid_file" ] && ps $(get_pid) > /dev/null 2>&1
    }
    START=99
    start() {
        if is_running; then
            echo "Already started"
        else
            echo "Starting $name"
            $cmd >> "$stdout_log" 2>> "$stderr_log" &
            echo $! > "$pid_file"
        fi
    }
    stop() {
        if is_running; then
            echo -n "Stopping $name.."
            kill $(get_pid)
            for i in {1..10}
            do
                if ! is_running; then
                    break
                fi
                echo -n "."
                sleep 1
            done
            echo
            if is_running; then
                echo "Not stopped; may still be shutting down or shutdown may have failed"
                exit 1
            else
                echo "Stopped"
                if [ -f "$pid_file" ]; then
                    rm "$pid_file"
                fi
            fi
        else
            echo "Not running"
        fi
    }
  4. 启动服务 /etc/init.d/cloudflared start