Ubuntu部署Wireguard

# 更新镜像并安装WireGuard
apt update && apt install -y wireguard

# 开启IP转发
echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
sysctl -p

2. 生成密钥对

# 创建配置目录
mkdir -p /etc/wireguard && chmod 0777 /etc/wireguard
cd /etc/wireguard
umask 077

# 生成服务器密钥
wg genkey | tee server_privatekey | wg pubkey > server_publickey

# 生成客户端密钥(可生成多个)
wg genkey | tee client1_privatekey | wg pubkey > client1_publickey

3. 服务端配置

# 创建配置文件(注意替换eth0为实际网卡名)
cat > wg0.conf <<EOF
[Interface]
PrivateKey = $(cat server_privatekey)
Address = 10.0.8.1/24
ListenPort = 50814
DNS = 8.8.8.8
MTU = 1420

# 流量转发规则(eth0需替换)
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]
# 客户端1配置
PublicKey = $(cat client1_publickey)
AllowedIPs = 10.0.8.10/32
EOF

4. 启动服务

# 设置开机自启
systemctl enable wg-quick@wg0

# 启动服务
wg-quick up wg0

# 检查状态
wg show

5. 客户端配置

# 生成客户端配置
cat > client1.conf <<EOF
[Interface]
PrivateKey = $(cat client1_privatekey)
Address = 10.0.8.10/32
DNS = 8.8.8.8
MTU = 1420

[Peer]
PublicKey = $(cat server_publickey)
Endpoint = [服务器公网IP]:50814
AllowedIPs = 0.0.0.0/0
PersistentKeepalive = 25
EOF

# 生成新客户端密钥
wg genkey | tee client2_privatekey | wg pubkey > client2_publickey

# 追加到wg0.conf
cat >> wg0.conf <<EOF

[Peer]
# 客户端2配置
PublicKey = $(cat client2_publickey)
AllowedIPs = 10.0.8.11/32
EOF

# 重载配置
wg syncconf wg0 <(wg-quick strip wg0)

链接:https://juejin.cn/post/7512058418623774735
来源:稀土掘金