Setting Up a Private VPN with Ngrok + OpenVPN in a Shared Network Environment

In scenarios like community-free networks where router access for port forwarding is not available, setting up a private VPN can be achieved using Ngrok and OpenVPN.

Install PiVPN and Choose OpenVPN (with TCP):

   sudo apt update -y && sudo apt upgrade -y
   curl -L https://install.pivpn.io | bash
  • Choose OpenVPN (not WireGuard, as it only supports UDP).
  • Set a local port, e.g., 11111.
  • Choose DNS, e.g., Google.
  • Select TCP.

Register and Install Ngrok:

   wget https://bin.equinox.io/c/bNyj1mQVY4c/ngrok-v3-stable-linux-amd64.tgz
   sudo tar -xvzf ngrok-v3-stable-linux-amd64.tgz -C /usr/local/bin
   ngrok config add-authtoken [yourToken]
  • Output will confirm auth-token is saved.

Map the Local Port with Ngrok:

   ngrok tcp 11111
  • Note down the output showing the session status and the forwarding TCP address (e.g., tcp://0.tcp.jp.ngrok.io:[remotedPort]).

Edit the .ovpn File Created by pivpn add:

  • Reflect the 0.tcp.jp.ngrok.io:[remotedPort] information in the file.
  • Note: With the free version of Ngrok, the [remotedPort] changes with each restart.

Now, You Should Be Able to Access the Internal Network Using OpenVPN.

Setting Up a Boot Startup Task File:

Create an Auto-start Task:

   crontab -e
  • Add the following line to start Ngrok with the system:
    @reboot nohup ngrok tcp 11111 > /path/to/ngrok.log 2>&1

Or you can make a daemon:

cd /etc/systemd/system
sudo touch ngrok.service
sudo chmod 644 ngrok.service

ngrok.service:

[Unit]
Description=Ngrok Service
After=network.target

[Service]
ExecStart=/home/username/dev/ngrok.sh > /tmp/ngrok.log 2>&1
Restart=on-failure
RestartSec=10s

[Install]
WantedBy=multi-user.target

ngrok.sh(make it executable):

#!/bin/bash
/usr/local/bin/ngrok config add-authtoken [yourToken]
/usr/local/bin/ngrok tcp [yourLocalPort]

then,

sudo systemctl daemon-reload
sudo systemctl restart ngrok.service

You can get the information of that randomized port used by ngrok:

curl http://127.0.0.1:4040/api/tunnels | jq '.tunnels[] | .public_url'

use OpenVPN in Linux as client side:

sudo openvpn --config [yourName].ovpn --connect-retry 0

留下评论

通过 WordPress.com 设计一个这样的站点
从这里开始