Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- set -e
- NS=wgnet
- QBIT=/usr/bin/qbittorrent-nox
- WGCONF=/etc/wireguard/wg0.conf
- PROFILE_DIR=/home/$USER/.config/qBittorrent
- echo "[*] Starting VPN + qBittorrent in namespace: $NS"
- # --- Create namespace if missing ---
- if ! ip netns list | grep -q "$NS"; then
- ip netns add "$NS"
- ip netns exec "$NS" ip link set lo up
- fi
- # --- Create veth pair (host <-> ns) ---
- if ! ip link show veth-host &>/dev/null; then
- ip link add veth-host type veth peer name veth-ns
- ip link set veth-ns netns $NS
- ip addr add 10.200.200.1/24 dev veth-host
- ip link set veth-host up
- ip netns exec $NS ip addr add 10.200.200.2/24 dev veth-ns
- ip netns exec $NS ip link set veth-ns up
- fi
- # --- Detect host's real internet interface ---
- HOST_IFACE=$(ip route get 1.1.1.1 | awk '{print $5; exit}')
- echo "[*] Host internet interface detected: $HOST_IFACE"
- # --- Enable NAT on host ---
- echo 1 > /proc/sys/net/ipv4/ip_forward
- iptables -t nat -C POSTROUTING -s 10.200.200.0/24 -o $HOST_IFACE -j MASQUERADE 2>/dev/null || \
- iptables -t nat -A POSTROUTING -s 10.200.200.0/24 -o $HOST_IFACE -j MASQUERADE
- # --- Extract VPN endpoint IP from wg0.conf ---
- VPN_ENDPOINT_IP=$(grep -i '^Endpoint' $WGCONF | awk '{print $3}' | cut -d: -f1)
- if [ -n "$VPN_ENDPOINT_IP" ]; then
- echo "[*] Adding route to VPN endpoint $VPN_ENDPOINT_IP via host"
- ip netns exec $NS ip route replace $VPN_ENDPOINT_IP via 10.200.200.1 dev veth-ns
- fi
- # --- Pre-tunnel default route via host (for handshake + DNS) ---
- ip netns exec $NS ip route replace default via 10.200.200.1 dev veth-ns
- # --- Start WireGuard inside namespace (no route changes, thanks to Table=off) ---
- ip netns exec $NS wg-quick down $WGCONF 2>/dev/null || true
- ip netns exec $NS wg-quick up $WGCONF
- # --- Wait for handshake ---
- echo "[*] Waiting for WireGuard handshake..."
- for i in {1..10}; do
- if ip netns exec $NS wg show | grep -q "latest handshake"; then
- echo "[✓] Handshake established"
- break
- fi
- sleep 2
- done
- # --- Replace default route with wg0 after handshake ---
- ip netns exec $NS ip route replace default dev wg0
- ip netns exec $NS ip -6 route replace default dev wg0 || true
- # --- DNS inside namespace ---
- mkdir -p /etc/netns/$NS
- cat > /etc/netns/$NS/resolv.conf <<EOF
- nameserver 1.1.1.1
- nameserver 1.0.0.1
- EOF
- # --- Restart qBittorrent ---
- PID=$(ip netns pids $NS | xargs -r ps -o pid=,comm= | awk '$2=="qbittorrent-nox"{print $1}')
- if [ -n "$PID" ]; then
- echo "[*] Killing old qbittorrent-nox (PID: $PID)"
- kill "$PID"
- sleep 2
- fi
- echo "[*] Starting qbittorrent-nox..."
- ip netns exec $NS sudo -u "$USER" $QBIT --profile=$PROFILE_DIR &
- echo "[✓] VPN + qBittorrent started inside namespace"
- echo "[✓] Access WebUI at: http://10.200.200.2:8080"
Add Comment
Please, Sign In to add comment