安装wireguard
首先执行系统更新
sudo apt update
等待更新结束后安装wireguard
sudo apt install wireguard
配置wireguard
配置新的接口
sudo vim /etc/wireguard/wg0.conf
复制配置文件
腾讯云
[Interface]
PrivateKey = XXXXXXXX
Address = 10.44.0.15/32
DNS = 10.44.0.1
[Peer]
PublicKey = XXXXXXXX
AllowedIPs = 192.168.50.0/23, 10.44.0.1/32
Endpoint = 域名:端口
阿里云
[Interface]
PrivateKey = XXXXXXXX=
Address = 10.44.0.18/32
DNS = 10.44.0.1
[Peer]
PublicKey = XXXXXXXX
AllowedIPs = 192.168.50.0/23, 10.44.0.1/32
Endpoint = 域名:端口
连接服务端
在连接之前,需要安装一个依赖包,否则会导致连接报错
Ubuntu24.04不需要安装
sudo apt install openresolv
连接服务端
sudo wg-quick up wg0
[#] ip link add wg0 type wireguard
[#] wg setconf wg0 /dev/fd/63
[#] ip -4 address add ##.1#.0.#/16 dev wg0
[#] ip link set mtu 1420 up dev wg0
[#] resolvconf -a wg0 -m 0 -x
Too few arguments.
Too few arguments.
[#] wg set wg0 fwmark 51820
[#] ip -4 route add 0.0.0.0/0 dev wg0 table 51820
[#] ip -4 rule add not fwmark 51820 table 51820
[#] ip -4 rule add table main suppress_prefixlength 0
[#] sysctl -q net.ipv4.conf.all.src_valid_mark=1
[#] iptables-restore -n
断开客户端连接
sudo wg-quick down wg0
显示当前的接口
sudo wg show
动态ip改变后自动重连
#!/bin/bash
# 配置文件路径
WG_CONF_FILE="/etc/wireguard/wg0.conf"
# 获取当前 WireGuard 接口 wg0 的 Peer Endpoint
CURRENT_ENDPOINT=$(wg show wg0 | grep 'endpoint' | awk '{print $2}' | cut -d ':' -f 1)
# 获取通过域名解析得到的公网 IP 地址(例如 www.wireguard.com)
MY_PUBLIC_IP=$(dig +short example.com)
# 检查当前 WireGuard 的 endpoint 是否是最新的
if [ "$CURRENT_ENDPOINT" != "$MY_PUBLIC_IP" ]; then
# 如果当前 endpoint 与域名解析后的 IP 地址不匹配,说明需要更新
echo "$(date) - Updating WireGuard endpoint from $CURRENT_ENDPOINT to $MY_PUBLIC_IP" >> ./ddns-wg0.log
# 更新 WireGuard 配置文件中的 endpoint
sed -i "s|Endpoint = .*|Endpoint = $MY_PUBLIC_IP:51820|" $WG_CONF_FILE
# 重启 WireGuard 接口
wg-quick down wg0
sleep 3
wg-quick up wg0
# 检查更新后的连接是否正常
if ! ping -c 3 $CURRENT_ENDPOINT > /dev/null 2>&1; then
echo "$(date) - Failed to restore WireGuard connection after updating endpoint." >> ./ddns-wg0.log
else
echo "$(date) - WireGuard connection successfully restored with updated endpoint." >> ./ddns-wg0.log
fi
else
# 如果当前的 endpoint 正常,不需要更新
echo "$(date) - WireGuard endpoint is up to date." >> ./ddns-wg0.log
fi
crontab
*/5 * * * * bash /home/data/checkwg.sh