Linux 配置 Wireguard 服务
·2 min read
for linux
[Interface]
Address = 10.14.0.2/24
PrivateKey = {Server PrivateKey}
ListenPort = 51821
PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -A FORWARD -o %i -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -D FORWARD -o %i -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE
[Peer]
AllowedIPs = 10.14.0.0/24
PublicKey = {Peer PublicKey}
for openwrt
# ===== 基本变量 =====
WG_IF="wg0"
WG_ADDR="10.14.0.1/24"
WG_PORT="51820"
SERVER_PRIVKEY="server_key"
# ===== 1. 接口 =====
uci -q delete network.$WG_IF
uci set network.$WG_IF="interface"
uci set network.$WG_IF.proto="wireguard"
uci set network.$WG_IF.private_key="$SERVER_PRIVKEY"
uci add_list network.$WG_IF.addresses="$WG_ADDR"
uci set network.$WG_IF.listen_port="$WG_PORT"
# ===== 2. Peers =====
add_peer () {
local PUBKEY=$1
local IP=$2
uci add network wireguard_$WG_IF
uci set network.@wireguard_$WG_IF[-1].public_key="$PUBKEY"
uci add_list network.@wireguard_$WG_IF[-1].allowed_ips="$IP/32"
uci set network.@wireguard_$WG_IF[-1].persistent_keepalive="25"
}
add_peer "peer_key" "10.14.0.3"
add_peer "peer_key" "10.14.0.4"
add_peer "peer_key" "10.14.0.5"
# ===== 3. firewall zone =====
uci -q delete firewall.wg
uci set firewall.wg="zone"
uci set firewall.wg.name="wg"
uci set firewall.wg.network="$WG_IF"
uci set firewall.wg.input="ACCEPT"
uci set firewall.wg.output="ACCEPT"
uci set firewall.wg.forward="ACCEPT"
# ===== 4. forwarding =====
uci -q delete firewall.wg_wan
uci set firewall.wg_wan="forwarding"
uci set firewall.wg_wan.src="wg"
uci set firewall.wg_wan.dest="wan"
# ===== 5. WAN NAT =====
WAN_ZONE=$(uci show firewall | grep ".name='wan'" | head -n1 | cut -d. -f2 | cut -d= -f1)
uci set firewall.$WAN_ZONE.masq="1"
uci set firewall.$WAN_ZONE.mtu_fix="1"
# ===== 提交 =====
uci commit network
uci commit firewall
/etc/init.d/network restart
/etc/init.d/firewall restart
echo "===== WireGuard 配置完成(稳定版)====="