保存时间:2026/4/2 19:13:25
wireguard - tools软件包中。wg是底层命令行工具,可直接通过命令行设置 WireGuard 接口的各项参数,如生成密钥、配置监听端口、设置允许的 IP 等。wg - quick基于wg,使用更便捷,通过配置文件来管理 WireGuard 接口,常用于启动、停止和重启 WireGuard 服务。wg genkey | tee wg - private.key | wg pubkey > wg - public.key命令生成私钥和公钥文件,然后修改文件权限,确保systemd - network用户可读取,如sudo chown root:systemd - network wg - private.key wg - public.key。/etc/systemd/network/目录下创建一个以.netdev为后缀的文件,如wg0.netdev,内容示例如下:[NetDev]
Name=wg0
Kind=wireguard
MTUBytes=1420
[WireGuard]
PrivateKeyFile=/path/to/wg - private.key
FirewallMark=4242
RouteTable=off
Name为接口名称,PrivateKeyFile指向私钥文件路径。3. 创建网络配置文件:在同一目录下创建一个以.network为后缀的文件,如wg0.network,内容示例如下:[Match]
Name=wg0
[Network]
Address=1.2.3.4/32
DNS=1.1.1.1
RoutingPolicyRules=family both, table main, suppress - prefix - length 0, priority 10
RoutingPolicyRules=family both, invert - rule true, firewall - mark 4242, table 4000, priority 11
Routes=destination 0.0.0.0/0, table 4000, scope link
Routes=destination ::/0, table 4000, scope link
[WireGuardPeers]
PublicKey=<the remote peer's public key here>
Endpoint=wg.example.com:51820
AllowedIPs=0.0.0.0/0, ::/0
PersistentKeepalive=25
Address为本地 WireGuard 接口的 IP 地址,PublicKey为对端公钥,Endpoint为对端地址和端口,AllowedIPs指定允许通过隧道访问的 IP 范围。4. 重载并启用配置:执行sudo systemctl reload systemd - networkd命令重载配置,然后使用sudo systemctl enable --now systemd - networkd命令启用systemd - networkd服务,WireGuard 接口将根据配置自动启动和管理。