个人技术空间关于本站

WireGuard 组网

环境 Ubuntu:24.04

虽然wireguard已经在 linux5.6+的内核中集成了,但是要通过命令行配置,还是要先安装相关工具

apt update
apt install wireguard -y

接下来生成当前机器的密钥,在每台机器上都要独立生成

mkdir -p /etc/wireguard/
cd /etc/wireguard/ 
wg genkey |tee privatekey | wg pubkey | tee publickey

下面为每台机器生成配置文件

配置解释

[Interface]
PrivateKey = 当前机器的私有密钥
Address = 当前主机的虚拟 IP 地址
ListenPort = 监听端口

[Peer]
PublicKey = 远程主机的公钥
PersistentKeepalive = 每隔多少秒发送一个空数据包,用于保活
AllowedIPs = 本地路由,访问这个 IP 的流量都发给这个远程主机
Endpoint = 远程主机的地址

假设有两台服务器要打通网络
A 机器配置
/etc/wireguard/wg0.conf配置文件

[Interface]
# A机器
PrivateKey = A 机器的privatekey内容
Address = 192.168.10.1/32
ListenPort = 30000

[Peer]
# B 机器
PublicKey = B机器的publickey内容
PersistentKeepalive = 60
AllowedIPs = 192.168.10.2/32
#B机器地址
Endpoint = 1.1.1.1:30000

B 机器配置
/etc/wireguard/wg0.conf配置文件

[Interface]
# B机器
PrivateKey = B 机器的privatekey内容
Address = 192.168.10.2/32
ListenPort = 30000

[Peer]
# A 机器
PublicKey = A机器的publickey内容
PersistentKeepalive = 60
AllowedIPs = 192.168.10.1/32
#B机器地址
Endpoint = 2.2.2.2:30000

假如 A、B 机器都可以公网访问,那么可以都双方配置Endpoint(也可以只配置单边)
假如 A 在公网,B 在内网的话,只需要在 B 机器配置上增加 A 机器的Endpoint。
假如 A、B 都在内网,需要至少其中一方设置端口映射,另一方连接端口映射后的地址。

设置开机启动

systemctl enable wg-quick@wg0
systemctl restart wg-quick@wg0

查看当前连接状态

wg

连接成功建立后,两台机器就可以通过虚拟 IP 进行通信了

CreateBy:2026-02-24,UpdateBy:2026-03-04

评论

还没有评论,欢迎第一个留言。
← 请输入您的姓名
← 请输入常用邮箱(不会公开)
← 请输入个人网站(可选)
← 请输入评论内容,文明交流
← 请先完成人机验证