补充说明
wg 命令 用于配置和控制 WireGuard 网络接口(配合 wg-quick 使用更简单)。WireGuard 是现代内核级 VPN:加密算法固定、代码量小、性能高、漫游无缝,是 VPS 间组网/科学上网的主流方案。
典型分工:wg-quick up wg0 读取 /etc/wireguard/wg0.conf 建隧道(含路由与 IP),wg 查看状态。
语法
wg [选项] 命令 [参数...]
命令
show 显示所有接口状态
show <interface> 显示指定接口
show <interface> peers 列出 peer 公钥
show <interface> private-key 显示私钥(谨慎)
genkey 生成随机私钥(stdout)
pubkey 从 stdin 私钥导出公钥
genpsk 生成预共享密钥
set <interface> <peer> ... 运行时修改配置
setconf <interface> <file> 整体替换配置
syncconf <interface> <file> 增量同步配置(不断连接)
实例
# 生成服务端/客户端密钥对
wg genkey | tee server.key | wg pubkey > server.pub
wg genkey | tee client.key | wg pubkey > client.pub
# 查看 VPN 隧道状态(握手时间、收发流量、允许的 IP)
sudo wg show
# 运行时添加一个 peer(公网中转节点常用)
sudo wg set wg0 peer <client-pub-key> allowed-ips 10.0.0.2/32
# 同步配置文件变更而不重启隧道
sudo wg syncconf wg0 <(wg-quick strip wg0)
配置文件示例(/etc/wireguard/wg0.conf,由 wg-quick 使用)
服务端(VPS):
[Interface]
Address = 10.0.0.1/24
ListenPort = 51820
PrivateKey = <server-private-key>
[Peer]
PublicKey = <client-public-key>
AllowedIPs = 10.0.0.2/32
客户端(全流量走 VPN):
[Interface]
Address = 10.0.0.2/24
PrivateKey = <client-private-key>
DNS = 1.1.1.1
[Peer]
PublicKey = <server-public-key>
Endpoint = vps.example.com:51820
AllowedIPs = 0.0.0.0/0
PersistentKeepalive = 25
配套命令
wg-quick:快速起停隧道(up/down/save/strip)sysctl net.ipv4.ip_forward=1:服务端开启转发ufw allow 51820/udp:放行端口