配置 WireGuard 的步骤如下:
安装 WireGuard 和相关工具
在服务器和客户端上安装 WireGuard 和必要的工具:
-
服务器(Ubuntu/Debian):
sudo apt update sudo apt install wireguard sudo apt install wg-quick2 python3-wg
-
客户端(Windows 或 macOS):
- 由于 WireGuard 原生不支持 Windows 和 macOS,可以使用第三方工具如
ZeroTier或OpenVPN,但这里以 Linux 为例。
- 由于 WireGuard 原生不支持 Windows 和 macOS,可以使用第三方工具如
生成密钥对
在服务器上生成密钥对:
wgctl create-conkeypair
生成后,密钥对位于 /etc/wireguard/,private.key 和 public.key。
配置服务器的 WireGuard 接口
创建并配置服务器接口:
wg create wg listen-port=12345 wg (interface) address = 172.16.254.1/24 save-allowed_ips = yes dhcp = yes ip6-assign = yes ip6-prefix = 64 mtu = 135 peer = [your_client_ip]/24 peerallowed = yes peer-allowed-ips = 0.../ peer-allowed-ips6 = 0:::::::/ persistent-keepalive = 10 redirect -i mask = 255.255.255. route-allowed = yes route-allowed6 = yes
启动服务器接口
在服务器上启动接口:
wg-quick2 up wg
配置客户端连接
在客户端上创建配置文件 client.conf:
sudo nano /etc/wireguard/config.pcfg
填入配置信息:
[interface] private-key-file = /etc/wireguard/private.key public-key-file = /etc/wireguard/public.key server-endpoint = your_server_ip:12345 allowed-ip = 0.../ allowed-ipprefix = /32 route-allowed = yes route-allowed6 = yes
启动客户端连接
在客户端上启动:
wg-quick2 up client
测试连接
检查接口状态:
ip link show wg
如果成功,接口将显示为 wg,状态为 up。
测试网络连通性:
ping your_server_ip
调整防火墙
确保防火墙允许 WireGuard 传输:
服务器:
sudo iptables -A POSTROUTING -o wg -j MASQUERADE sudo iptables -A FORWARD -i wg -j ACCEPT sudo iptables -A FORWARD -o wg -m state --state RELATED,ESTABLISHED -j ACCEPT
客户端:
sudo iptables -A POSTROUTING -o client -j MASQUERADE sudo iptables -A FORWARD -i client -j ACCEPT sudo iptables -A FORWARD -o client -m state --state RELATED,ESTABLISHED -j ACCEPT
优化性能(可选)
设置 MTU 和流量限制:
wgctl set wg mtu 135 wgctl set wg fw-mark 0 wgctl set wg strict-neighbor-validation 0 wgctl set wg fast-path 0 wgctl set wg allowed-ips 0.../
额外配置
如果需要多个接口或服务器:
wg create wg1wg-quick2 up wg1
通过以上步骤,您可以成功配置 WireGuard,建立安全高效的网络连接,遇到问题时,可参考 WireGuard 文档或社区获取帮助。









