用WireGuard和RouterOS实现多局域网直连:让异地办公室像在同一个房间聊天!

|

前言:当你的办公室分布在天南地北…

想象一下这个场景:你的公司总部在北京,分公司在上海,研发中心在深圳,还有个居家办公的员工在海南。每次开会都像是在组织一场跨国会议,访问共享文件比登天还难,VPN慢得像蜗牛爬… 😫

别担心!今天我要分享的神奇方案,能让这些分布在各地的局域网像在同一个房间里一样直接聊天!而且最棒的是——数据完全不经过中转服务器,速度飞起!

方案原理:WireGuard的”相亲大会”

我们的方案就像是一个高效的”相亲中介”:

  1. 云服务器:就像一个相亲网站,负责记录每个人的”联系方式”(公网IP和端口)
  2. 各个局域网:就像参加相亲的男女嘉宾,都连接到这个网站
  3. WireGuard:就像每个人的”对讲机”,可以直接通话

关键点

  • 相亲网站(云服务器)只负责交换联系方式,不负责传话
  • 嘉宾们(局域网)拿到联系方式后,直接使用对讲机(WireGuard)聊天
  • 即使有人搬家换了地址(NAT重绑定),网站也会及时更新信息

准备工作:你需要什么?

硬件清单 🛠️

  1. 云服务器:1台,有公网IP(阿里云、腾讯云、AWS等都行)
  • 系统:Ubuntu 20.04/22.04
  • 配置:1核1G就够用
  • 流量:按需选择,反正不中转数据
  1. RouterOS设备:每个局域网1台,版本v7.x
  • 可以是MikroTik任意型号
  • 或者x86软路由安装RouterOS
  1. 网络环境
  • 每个局域网有不同的网段(如192.168.88.0/24、192.168.89.0/24等)
  • 路由器能进行端口转发

软件工具 🧰

  1. WinBox:配置RouterOS的神器
  2. SSH客户端:连接云服务器
  3. 一杯咖啡:配置时需要保持清醒 ☕

第一部分:云服务器搭建(我们的”相亲网站”)

步骤1:登录云服务器

# 使用SSH登录你的云服务器
ssh root@你的服务器IP
# 输入密码,然后我们就进入战斗状态!

步骤2:安装WireGuard(比安装微信还简单)

# 更新系统(就像每天早上刷新朋友圈)
sudo apt update && sudo apt upgrade -y

# 安装WireGuard(一键安装,毫无难度)
sudo apt install wireguard wireguard-tools -y

# 检查是否安装成功(看到版本号就OK)
wg --version

步骤3:生成服务器密钥(创建网站账号)

# 进入WireGuard配置目录
cd /etc/wireguard

# 生成密钥对(公钥私钥,就像账号密码)
sudo wg genkey | tee server-private.key | wg pubkey > server-public.key

# 查看公钥(记下来,后面要用)
echo "服务器的公钥是:"
cat server-public.key

步骤4:创建WireGuard配置文件

# 创建配置文件
sudo nano /etc/wireguard/wg0.conf

在文件中输入以下内容(记得替换[你的服务器私钥]):

[Interface]
Address = 10.200.200.1/24
ListenPort = 51820
PrivateKey = [你的服务器私钥]

# 允许IP转发(重要!不然数据包就卡住了)
PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE

# 注意:这里先不添加[Peer]部分,等客户端准备好再加

Ctrl+X,然后按Y,再按Enter保存。

步骤5:创建智能API服务(网站的”大脑”)

# 创建项目目录
sudo mkdir -p /opt/wg-mesh
cd /opt/wg-mesh

# 创建Python虚拟环境(就像给应用单独一个房间)
sudo apt install python3 python3-pip python3-venv -y
sudo python3 -m venv venv

# 激活虚拟环境并安装Flask
sudo venv/bin/pip install flask

步骤6:编写智能API代码

# 创建主程序文件
sudo nano /opt/wg-mesh/mesh-api.py

粘贴以下代码(代码有点长,但别怕,都是复制粘贴的活):

#!/usr/bin/env python3
"""
WireGuard Mesh API - 让所有局域网自动找到彼此
作者:Huwencai.com
功能:自动发现、自动连接、自动更新
"""

from flask import Flask, request, jsonify
import subprocess
import re
from datetime import datetime
import threading

app = Flask(__name__)

# 线程锁,防止多个人同时修改数据打架
lock = threading.Lock()

def parse_wg_show():
    """解析wg show的输出,提取所有对端信息"""
    try:
        # 执行wg show命令
        result = subprocess.run(
            ['wg', 'show', 'wg0'],
            capture_output=True,
            text=True,
            check=True
        )

        peers = {}
        current_peer = None

        # 逐行解析输出
        for line in result.stdout.split('\n'):
            line = line.strip()

            # 发现新的对等端
            if line.startswith('peer:'):
                if current_peer and 'public_key' in current_peer:
                    peers[current_peer['public_key']] = current_peer

                public_key = line[5:].strip()
                current_peer = {
                    'public_key': public_key,
                    'endpoint': None,
                    'allowed_ips': [],
                    'latest_handshake': None,
                    'wireguard_ip': None,
                    'lan_networks': []
                }

            # 提取endpoint(打洞信息)
            elif line.startswith('endpoint:'):
                if current_peer:
                    current_peer['endpoint'] = line[9:].strip()

            # 提取允许的IP地址
            elif line.startswith('allowed ips:'):
                if current_peer:
                    ips = line[12:].strip().split(', ')
                    current_peer['allowed_ips'] = ips

                    # 区分WireGuard隧道IP和局域网网段
                    for ip in ips:
                        if ip.endswith('/32'):
                            current_peer['wireguard_ip'] = ip.split('/')[0]
                        else:
                            current_peer['lan_networks'].append(ip)

            # 提取最近握手时间
            elif line.startswith('latest handshake:'):
                if current_peer:
                    current_peer['latest_handshake'] = line[18:].strip()

        # 别忘了最后一个对等端
        if current_peer and 'public_key' in current_peer:
            peers[current_peer['public_key']] = current_peer

        return peers

    except Exception as e:
        print(f"解析wg show时出错: {e}")
        return {}

@app.route('/api/peers', methods=['GET'])
def get_peers():
    """
    获取所有可连接的对端(排除自己和没有endpoint的)
    客户端通过这个接口找到其他局域网
    """
    with lock:
        # 解析当前WireGuard状态
        all_peers = parse_wg_show()

        # 获取客户端IP(从WireGuard隧道)
        client_ip = request.remote_addr

        # 找出客户端对应的对等端信息
        client_info = None
        for peer in all_peers.values():
            if peer.get('wireguard_ip') == client_ip:
                client_info = peer
                break

        # 如果客户端不在列表中,拒绝访问
        if not client_info:
            return jsonify({
                'error': '未授权的访问',
                'message': '请先连接到WireGuard服务器'
            }), 403

        # 收集其他对端信息(排除自己,且必须有endpoint)
        other_peers = []
        for pub_key, peer in all_peers.items():
            # 排除自己
            if pub_key == client_info['public_key']:
                continue

            # 只返回有endpoint的对端(已经成功打洞的)
            if peer.get('endpoint'):
                other_peers.append({
                    'public_key': pub_key,
                    'endpoint': peer['endpoint'],
                    'wireguard_ip': peer.get('wireguard_ip'),
                    'lan_networks': peer.get('lan_networks', []),
                    'latest_handshake': peer.get('latest_handshake')
                })

        return jsonify({
            'client': {
                'public_key': client_info['public_key'],
                'wireguard_ip': client_info.get('wireguard_ip'),
                'lan_networks': client_info.get('lan_networks', [])
            },
            'peers': other_peers,
            'total': len(other_peers),
            'timestamp': datetime.now().isoformat()
        })

@app.route('/api/status', methods=['GET'])
def get_status():
    """查看系统状态(管理员用)"""
    with lock:
        peers = parse_wg_show()

        status = {
            'total_peers': len(peers),
            'active_peers': len([p for p in peers.values() if p.get('endpoint')]),
            'inactive_peers': len([p for p in peers.values() if not p.get('endpoint')]),
            'peers': []
        }

        for pub_key, peer in peers.items():
            status['peers'].append({
                'public_key_short': pub_key[:16] + '...',
                'has_endpoint': peer.get('endpoint') is not None,
                'endpoint': peer.get('endpoint', '等待连接...'),
                'wireguard_ip': peer.get('wireguard_ip'),
                'lan_networks': peer.get('lan_networks', []),
                'latest_handshake': peer.get('latest_handshake')
            })

        return jsonify(status)

@app.route('/api/health', methods=['GET'])
def health():
    """健康检查"""
    return jsonify({
        'status': 'healthy',
        'service': 'wireguard-mesh',
        'time': datetime.now().isoformat()
    })

if __name__ == '__main__':
    print("WireGuard Mesh API 启动中...")
    print("监听地址: 10.200.200.1:8000")
    print("访问 http://10.200.200.1:8000/api/status 查看状态")
    app.run(host='10.200.200.1', port=8000, debug=False)

Ctrl+XYEnter保存。

步骤7:创建系统服务(让API自动运行)

# 创建服务文件
sudo nano /etc/systemd/system/wg-mesh-api.service

粘贴以下内容:

[Unit]
Description=WireGuard Mesh API Service
[email protected]
[email protected]

[Service]
Type=simple
User=root
WorkingDirectory=/opt/wg-mesh
ExecStart=/opt/wg-mesh/venv/bin/python /opt/wg-mesh/mesh-api.py
Restart=always
RestartSec=10
Environment="PYTHONUNBUFFERED=1"

[Install]
WantedBy=multi-user.target

步骤8:启动所有服务

# 启用IP转发(让数据包能通过服务器转发)
sudo sed -i 's/#net.ipv4.ip_forward=1/net.ipv4.ip_forward=1/' /etc/sysctl.conf
sudo sysctl -p

# 启动WireGuard
sudo systemctl enable wg-quick@wg0
sudo systemctl start wg-quick@wg0

# 启动API服务
sudo systemctl enable wg-mesh-api
sudo systemctl start wg-mesh-api

# 检查状态(两个都应该是active)
sudo systemctl status wg-quick@wg0
sudo systemctl status wg-mesh-api

步骤9:测试API服务

# 测试API是否正常工作
curl http://localhost:8000/api/health
# 应该返回:{"status":"healthy","service":"wireguard-mesh"}

# 查看WireGuard状态
sudo wg show
# 这时应该只有服务器信息,没有peers

恭喜!云服务器部分配置完成! 🎉

现在你的”相亲网站”已经搭建好了,接下来就是邀请”嘉宾”(各个局域网)加入了。

第二部分:配置第一个局域网(RouterOS-A)

假设这是北京总部的路由器,局域网网段:192.168.88.0/24

步骤1:登录RouterOS

  1. 打开WinBox
  2. 输入路由器IP地址、用户名、密码
  3. 点击”Connect”

步骤2:创建WireGuard接口(给路由器装”对讲机”)

  1. 左侧菜单点击 Interfaces
  2. 点击 WireGuard 标签
  3. 点击蓝色的 +
  4. 配置如下:
  • Name: wg-mesh (名字随便取,好记就行)
  • Listen Port: 51820 (默认端口,可以改)
  • 点击 Generate New 生成密钥对
  • Public Key 会自动显示,记下来!(后面要添加到云服务器)
  1. 点击 ApplyOK

步骤3:分配隧道IP(给对讲机一个频道)

  1. 左侧菜单点击 IPAddresses
  2. 点击 +
  3. 配置:
  • Address: 10.200.200.2/24 (第一个客户端用.2)
  • Network: 10.200.200.0
  • Interface: 选择刚才创建的 wg-mesh
  1. 点击 ApplyOK

步骤4:添加云服务器为对等端(连接相亲网站)

  1. 回到 InterfacesWireGuard
  2. 双击刚才创建的 wg-mesh 接口
  3. 点击 Peers 标签页
  4. 点击 +
  5. 配置:
  • Public Key: [粘贴云服务器的公钥]
  • Endpoint Address: [云服务器的公网IP]
  • Endpoint Port: 51820
  • Allowed Address: 10.200.200.0/24
  • Persistent Keepalive: 25 (保持连接活跃)
  1. 点击 ApplyOK

步骤5:在云服务器上添加这个客户端

回到云服务器的SSH窗口,执行:

# 添加RouterOS-A为对等端
sudo wg set wg0 peer [粘贴RouterOS-A的公钥] allowed-ips 10.200.200.2/32,192.168.88.0/24 persistent-keepalive 25

# 保存配置
sudo wg-quick save wg0

# 检查是否添加成功
sudo wg show
# 现在应该能看到一个peer,但endpoint还是空的(等客户端连接后才有)

步骤6:创建智能发现脚本(让路由器自动找朋友)

  1. 左侧菜单点击 SystemScripts
  2. 点击 +
  3. 配置:
  • Name: mesh-auto-discover
  • Source 框中粘贴以下脚本:
{
# ============================================
# WireGuard Mesh 自动发现脚本
# 功能:自动发现其他局域网并建立直连
# 作者:Huwencai.com
# ============================================

# 配置信息
:local apiServer "10.200.200.1:8000"
:local wgInterface "wg-mesh"
:local myLanNetworks "192.168.88.0/24"

# 记录开始时间(用来计算执行时间)
:local startTime [/system clock get time]

# 1. 从API获取所有可连接的对端
:log info "开始搜索其他局域网..."
/tool fetch url="http://$apiServer/api/peers" mode=http dst-path="/tmp/peers.json"

:local response [/file get [/file find name="peers.json"] contents]
/file remove [/file find name="peers.json"]

:if ([:len $response] < 10) do={
    :log warning "API无响应,请检查网络连接"
    :return
}

:try {
    # 解析JSON响应
    :local jsonObj [:parse $response]
    :local peers ($jsonObj->"peers")
    :local totalPeers ($jsonObj->"total")

    :log info "发现 $totalPeers 个可连接的对端"

    # 2. 获取当前已存在的动态对等端
    :local existingDynamicPeers [:toarray ""]
    :local allCurrentPeers [/interface wireguard peers find where interface=$wgInterface]

    :foreach peerIdx in $allCurrentPeers do={
        :local peerComment [/interface wireguard peers get $peerIdx comment]
        :if ([:find $peerComment "mesh-auto:"] = 0) do={
            :local pubKey [/interface wireguard peers get $peerIdx public-key]
            :set ($existingDynamicPeers->[:len $existingDynamicPeers]) $pubKey
        }
    }

    # 3. 处理每个发现的對端
    :local addedCount 0
    :local updatedCount 0

    :foreach i in=[:range 0 $totalPeers - 1] do={
        :local peer ($peers->$i)
        :local peerPubKey ($peer->"public_key")
        :local peerEndpoint ($peer->"endpoint")
        :local peerLanNetworks ($peer->"lan_networks")
        :local peerWireguardIp ($peer->"wireguard_ip")

        # 只处理有endpoint的对端(已经打洞成功的)
        :if ([:len $peerEndpoint] > 0) do={
            # 构建allowed addresses(允许访问的IP范围)
            :local allowedAddresses ""
            :foreach lanNet in $peerLanNetworks do={
                :if ([:len $allowedAddresses] = 0) do={
                    :set allowedAddresses $lanNet
                } else={
                    :set allowedAddresses ($allowedAddresses . "," . $lanNet)
                }
            }

            # 添加WireGuard隧道IP
            :if ([:len $peerWireguardIp] > 0) do={
                :if ([:len $allowedAddresses] = 0) do={
                    :set allowedAddresses ($peerWireguardIp . "/32")
                } else={
                    :set allowedAddresses ($allowedAddresses . "," . $peerWireguardIp . "/32")
                }
            }

            # 检查是否已存在此对等端
            :local existingPeer [/interface wireguard peers find where interface=$wgInterface && public-key=$peerPubKey]

            :if ([:len $existingPeer] = 0) do={
                # 添加新的对等端(建立直连)
                /interface wireguard peers add interface=$wgInterface \
                    public-key=$peerPubKey \
                    endpoint=$peerEndpoint \
                    allowed-address=$allowedAddresses \
                    persistent-keepalive=25s \
                    comment=("mesh-auto:" . $peerWireguardIp)

                :set addedCount ($addedCount + 1)
                :log info "✅ 新增直连: $peerWireguardIp ($peerEndpoint)"
            } else={
                # 检查是否需要更新
                :local currentEndpoint [/interface wireguard peers get $existingPeer value-name=endpoint-address]
                :local currentAllowed [/interface wireguard peers get $existingPeer value-name=allowed-address]

                :local needsUpdate false

                :if ($currentEndpoint != $peerEndpoint) do={
                    /interface wireguard peers set $existingPeer endpoint-address=$peerEndpoint
                    :set needsUpdate true
                }

                :if ($currentAllowed != $allowedAddresses) do={
                    /interface wireguard peers set $existingPeer allowed-address=$allowedAddresses
                    :set needsUpdate true
                }

                :if ($needsUpdate = true) do={
                    :set updatedCount ($updatedCount + 1)
                    :log info "🔄 更新连接: $peerWireguardIp"
                }
            }

            # 从现有列表中移除(表示这个对端还存在)
            :local newExistingPeers [:toarray ""]
            :foreach existingPubKey in $existingDynamicPeers do={
                :if ($existingPubKey != $peerPubKey) do={
                    :set ($newExistingPeers->[:len $newExistingPeers]) $existingPubKey
                }
            }
            :set existingDynamicPeers $newExistingPeers
        }
    }

    # 4. 清理不再存在的对等端
    :foreach stalePubKey in $existingDynamicPeers do={
        :local stalePeer [/interface wireguard peers find where interface=$wgInterface && public-key=$stalePubKey]
        :if ([:len $stalePeer] > 0) do={
            /interface wireguard peers remove $stalePeer
            :log info "🗑️ 移除过期连接: $stalePubKey"
        }
    }

    # 5. 添加路由(让数据包知道怎么走)
    :foreach i in=[:range 0 $totalPeers - 1] do={
        :local peer ($peers->$i)
        :local peerLanNetworks ($peer->"lan_networks")
        :local peerWireguardIp ($peer->"wireguard_ip")

        :foreach lanNet in $peerLanNetworks do={
            :local routeExists [/ip route find where dst-address=$lanNet]
            :if ([:len $routeExists] = 0) do={
                /ip route add dst-address=$lanNet gateway=$peerWireguardIp distance=1
                :log info "🛣️ 添加路由: $lanNet -> $peerWireguardIp"
            }
        }
    }

    # 6. 记录执行结果
    :local endTime [/system clock get time]
    :local duration ($endTime - $startTime)

    :log info "========================================"
    :log info "自动发现完成!"
    :log info "新增连接: $addedCount 个"
    :log info "更新连接: $updatedCount 个"
    :log info "移除连接: [:len $existingDynamicPeers] 个"
    :log info "总对端数: $totalPeers 个"
    :log info "执行时间: $duration 秒"
    :log info "========================================"

} :catch (error) {
    :log error "脚本执行出错: $error"
}
}
  1. 点击 ApplyOK

步骤7:创建定时任务(定期刷新朋友列表)

  1. 左侧菜单点击 SystemScheduler
  2. 点击 +
  3. 配置:
  • Name: mesh-auto-update
  • Interval: 00:01:00 (每1分钟执行一次)
  • On Event: 选择 mesh-auto-discover
  1. 点击 ApplyOK

步骤8:配置防火墙(开门迎客)

允许WireGuard入站连接:

  1. 左侧菜单点击 IPFirewall
  2. 点击 Filter Rules 标签页
  3. 点击 +
  4. 配置:
  • Chain: input
  • Protocol: udp
  • Dst. Port: 51820
  • Action: accept
  • Comment: 允许WireGuard入站
  1. 点击 ApplyOK

允许转发WireGuard流量:

  1. 再次点击 +
  2. 配置:
  • Chain: forward
  • In. Interface: 选择 wg-mesh
  • Action: accept
  • Comment: 允许转发WireGuard入站流量
  1. 点击 ApplyOK
  2. 再点击 +
  3. 配置:
  • Chain: forward
  • Out. Interface: 选择 wg-mesh
  • Action: accept
  • Comment: 允许转发WireGuard出站流量
  1. 点击 ApplyOK

步骤9:配置NAT端口转发(让外部能连进来)

  1. 点击 NAT 标签页
  2. 点击 +
  3. 配置:
  • Chain: dstnat
  • Protocol: udp
  • Dst. Port: 51820
  • In. Interface: [选择你的WAN口,通常是ether1]
  • Action: dst-nat
  • To Addresses: [路由器内网IP,如192.168.88.1]
  • To Ports: 51820
  • Comment: WireGuard端口转发
  1. 点击 ApplyOK

步骤10:测试连接

  1. 手动运行一次脚本:
  • SystemScripts
  • 双击 mesh-auto-discover
  • 点击 Run Script
  1. 查看日志:
  • LogSystem
  • 应该能看到类似这样的信息:
    发现 X 个可连接的对端 新增直连: 10.200.200.3 (xxx.xxx.xxx.xxx:51820)
  1. 检查WireGuard状态:
  • InterfacesWireGuard
  • 双击 wg-mesh
  • 点击 Peers 标签页
  • 应该能看到云服务器和其他局域网的连接

恭喜!第一个局域网配置完成! 🎊

第三部分:配置第二个局域网(RouterOS-B)

假设这是上海分公司的路由器,局域网网段:192.168.89.0/24

重复第二部分的所有步骤,但注意以下不同点:

不同点列表:

  1. WireGuard隧道IP:使用 10.200.200.3/24(不能重复)
  2. 局域网网段:脚本中的 myLanNetworks 改为 "192.168.89.0/24"
  3. 在云服务器添加时
   sudo wg set wg0 peer [RouterOS-B的公钥] allowed-ips 10.200.200.3/32,192.168.89.0/24 persistent-keepalive 25

快速配置检查表:

  • [ ] WireGuard接口名称:wg-mesh
  • [ ] 隧道IP:10.200.200.3/24
  • [ ] 脚本中的局域网网段:192.168.89.0/24
  • [ ] 防火墙规则已添加
  • [ ] NAT端口转发已配置
  • [ ] 定时任务已创建

第四部分:测试整个系统

测试1:检查云服务器状态

# 在云服务器上执行
sudo wg show
# 应该看到两个peer,都有endpoint信息

curl http://localhost:8000/api/status
# 应该看到两个活跃对端

测试2:从北京ping上海

在北京的RouterOS上:

  1. ToolsPing
  2. 地址输入:10.200.200.3(上海的隧道IP)
  3. 点击 Start
  4. 应该能ping通!

测试3:从北京访问上海的局域网

在北京局域网的任意电脑上:

ping 192.168.89.1

应该能ping通上海路由器的内网IP!

测试4:查看直连状态

在北京的RouterOS上:

  1. InterfacesWireGuard
  2. 双击 wg-mesh
  3. 点击 Peers 标签页
  4. 找到上海的连接,查看 Latest Handshake(应该是几秒前)

第五部分:添加更多局域网(无限扩展!)

想要添加深圳办公室?海南居家办公?完全没问题!

添加新局域网的步骤:

  1. 在新路由器上
  • 重复第二部分的所有步骤
  • 使用新的隧道IP(如 10.200.200.4/24
  • 设置正确的局域网网段
  1. 在云服务器上
   # 假设是第三个局域网,网段192.168.90.0/24
   sudo wg set wg0 peer [新路由器公钥] allowed-ips 10.200.200.4/32,192.168.90.0/24 persistent-keepalive 25
   sudo wg-quick save wg0
  1. 自动发现
  • 现有局域网会自动发现新加入的局域网
  • 新局域网也会自动发现所有现有局域网

第六部分:故障排除(遇到问题看这里)

问题1:脚本执行报错

症状:日志中出现错误信息
解决

  1. 检查API地址是否正确:10.200.200.1:8000
  2. 检查是否能ping通API服务器:ping 10.200.200.1
  3. 检查云服务器防火墙:sudo ufw allow 8000/tcp

问题2:WireGuard没有握手

症状:Latest Handshake显示很久以前
解决

  1. 检查NAT端口转发是否正确
  2. 检查防火墙是否允许UDP 51820
  3. 尝试重启WireGuard接口:
   /interface wireguard disable wg-mesh
   /interface wireguard enable wg-mesh

问题3:能ping通隧道IP,但ping不通局域网IP

症状:能ping通10.200.200.x,但ping不通192.168.xx.xx
解决

  1. 检查路由表:/ip route print
  2. 检查对方路由器的防火墙是否允许转发
  3. 检查脚本中的allowed-address是否包含局域网网段

问题4:连接不稳定,时断时续

症状:连接经常断开
解决

  1. 增加Persistent Keepalive时间:改为30秒
  2. 检查网络是否有UDP限制
  3. 考虑使用固定端口映射

问题5:云服务器API无法访问

症状:路由器无法连接到API
解决

# 在云服务器上检查
sudo systemctl status wg-mesh-api
sudo netstat -tlnp | grep 8000
# 如果端口没监听,重启服务
sudo systemctl restart wg-mesh-api

第七部分:高级优化(让网络更快更稳)

优化1:调整更新频率

如果网络稳定,可以降低更新频率:

  • 修改定时任务的Interval为 00:05:00(5分钟)

优化2:添加健康检查

创建健康检查脚本:

{
:local wgInterface "wg-mesh"
:local peers [/interface wireguard peers find where interface=$wgInterface]

:foreach peerIdx in $peers do={
    :local lastHandshake [/interface wireguard peers get $peerIdx latest-handshake]
    :local now [/system clock get time]

    :if ($now - $lastHandshake > 180) do={
        :log warning "对端 $peerIdx 超过3分钟无响应"
        # 可以在这里添加自动修复逻辑
    }
}
}

优化3:添加通知功能

当有新局域网加入时发送通知(邮件、微信等)。

第八部分:安全注意事项

  1. API安全:我们的API只监听WireGuard隧道IP,相对安全
  2. WireGuard安全:使用公钥认证,比密码更安全
  3. 防火墙:只开放必要的端口
  4. 定期更新:定期更新RouterOS和云服务器系统

结语:享受你的零延迟异地网络!

现在,你的各个办公室已经通过WireGuard直连起来了!无论它们分布在哪里,都像是坐在同一个办公室里一样。

关键优势

  • 零延迟:数据直连,不经过中转
  • 自动发现:新加入的局域网自动被所有局域网发现
  • 动态更新:NAT变化自动适应
  • 无限扩展:支持任意数量的局域网
  • 简单配置:每个路由器只需配置一次

如果你在配置过程中遇到任何问题,欢迎在博客评论区留言讨论。如果你觉得这篇文章有帮助,请分享给更多需要的人!

类似文章

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注